2010-06-15 9 views
6
#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(); 
} 

Die Ausgabe lautet:Life Scope von temporären Variablen

--> 
--> Hello World 

Hallo, darf ich weiß, das richtige Verhalten Garantie von C++ Standard ist, oder es hängt von Ihren Compiler-Anbieter-Implementierungen? Ich habe dies unter VC2008 und VC6 getestet. Funktioniert gut für beide.

+1

Duplizieren von: http://stackoverflow.com/questions/2506793/c-life-span-of-temporary-arguments –

+0

Übrigens kann Ihre 'Get'-Funktion vereinfacht werden: std :: string get () {zurück "Hallo Welt"; } – fredoverflow

Antwort

10

Siehe this question. Der Standard garantiert, dass ein vorläufiges Leben bis zum Ende des Ausdrucks, zu dem es gehört, existiert. Da der gesamte Funktionsaufruf der Ausdruck ist, wird das temporäre garantiert bis nach dem Ende des Funktionsaufrufausdrucks, in dem es ein Teil ist.

Verwandte Themen