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字符串臨時局部值?
該函數獲取兩個指針,那麼爲什麼它是一個值的調用?
對不起,我認爲這是一個非常愚蠢的問題,但我不明白。
謝謝。