The life scale of a temporary variable
#include <cstdio> #include <string> void fun(const char* c) { printf("--> %s\n", c); } std::string get() { std::string str = "Hello World"; return str; } int main() { const char *cc = get().c_str(); // cc is not valid at this point. As it is pointing to // temporary string internal buffer, and the temporary string // has already been destroyed at this point. fun(cc); // But I am surprise this call will yield valid result. // It seems that the returned temporary string is valid within // scope (...) // What my understanding is, scope means {...} // Is this valid behavior guarantee by C++ standard? Or it depends // on your compiler vendor implementations? fun(get().c_str()); getchar(); } Output:
--> --> Hello World Hello, can I know that the correct behavior is guaranteed by the C ++ standard, or does it depend on your compiler provider implementations? I tested this under VC2008 and VC6. Works great for both.
See this question . The standard ensures that the temporary lifespan is until the end of the expression of which it is a part. Since the call to the entire function is an expression, the temporary one is guaranteed to remain until the function call expression in which it is a part ends.