2010-06-15 17 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(); 
} 

wyjście jest:Życie Zakres zmiennej tymczasowej

--> 
--> Hello World 

Witam, mogę wiedzieć prawidłowe zachowanie jest gwarancją przez C++ standardzie, albo zależy od implementacji dostawcy kompilatora? Przetestowałem to pod VC2008 i VC6. Działa dobrze dla obu.

+1

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

+0

Nawiasem mówiąc, twoja funkcja 'get' może zostać uproszczona do: std :: string get () {return "Hello World"; } – fredoverflow

Odpowiedz

10

Zobacz this question. Standard gwarantuje, że tymczasowe życie trwa do końca wyrażenia, którego jest częścią. Ponieważ całe wywołanie funkcji jest wyrażeniem, tymczasowy jest gwarantowany do końca po zakończeniu wyrażenia wywołania funkcji, w którym jest częścią.

Powiązane problemy