0

これは私の問題です:

/**
* Example of the book:
* C++ Templates page 17/18
*/

#include <iostream>
#include <cstring>
#include <string>

// max of two values of any type (call by reference)
template <typename T>
inline T const& max (T const& a, T const& b) {
    return a < b ? b : a;
}

// max of two C-strings (call by value) 
inline char const* max (char const* a, char const* b) {
    // ??? Creates this a new temporary local value that may be returned?
    // I can't see where the temporary value is created!
    return std::strcmp(a,b) < 0 ? b : a;
}

// max of three values of any type (call by reference)
template <typename T>
inline T const& max (T const& a, T const& b, T const& c) {
    return max (max(a,b),c); // warning "error", if max(a,b) uses call-by-value
                             // warning:  reference of temp value will be returned

int main() {
    // call by reference 
    std::cout << ::max(7, 42, 68) << std::endl;

    const char* s1 = "Tim";
    const char* s2 = "Tom";
    const char* s3 = "Toni";
    // call the function with call by value
    // ??? Is this right?
    std::cout << ::max(s1,s2) << std::endl;

    std::cout << ::max(s1, s2, s3) << std::endl;
}

C文字列のmax関数の一時的なローカル値はどこにありますか?

この関数は 2 つのポインターを取得するのに、なぜ値渡しなのですか?

申し訳ありませんが、それは非常にばかげた質問だと思いますが、理解できません。

ありがとうございました。

4

1 に答える 1

2

C文字列のmax関数の一時的なローカル値はどこにありますか?

以下:

return std::strcmp(a,b) < 0 ? b : a;

次と同等です。

const char *ret = std::strcmp(a,b) < 0 ? b : a;
return ret;

問題の「一時的なローカル値」は、名前のないret.

この関数は 2 つのポインターを取得するのに、なぜ値渡しなのですか?

各 C 文字列は で表されconst char*const char*は値で渡されます。つまり、関数がaor b(つまり、ポインター自体) を変更した場合、その変更は呼び出し元には表示されません。

于 2013-01-04T12:06:05.460 に答える