Когда временные значения параметров выходят за рамки? [Дубликат]
Possible Duplicate:
Lifetime of temporaries
int LegacyFunction(const char *s) {
// do something with s, like print it to standard output
// this function does NOT retain any pointer to s after it returns.
return strlen(s);
}
std::string ModernFunction() {
// do something that returns a string
return "Hello";
}
LegacyFunction(ModernFunction().c_str());
Приведенный выше пример можно легко переписать, чтобы использовать умные указатели вместо строк; Я сталкивался с обеими этими ситуациями много раз. В любом случае, приведенный выше пример создаст строку STL в ModernFunction, вернет ее, затем получит указатель на строку в стиле C внутри строкового объекта и затем передаст этот указатель в унаследованную функцию.
There is a temporary string object that exists after ModernFunction has returned. When does it go out of scope? Is it possible for the compiler to call c_str(), destruct this temporary string object, and then pass a dangling pointer to LegacyFunction? (Remember that the string object is managing the memory that c_str() return value points to...) If the above code is not safe, why is it not safe, and is there a better, equally concise way to write it than adding a temporary variable when making the function calls? If it's safe, why?