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

La salida es:Vida Ámbito de variable temporal

--> 
--> Hello World 

Hola, se puede saber el comportamiento correcto es garantía de C++ estándar, o que depende de sus implementaciones de proveedores compilador? He probado esto en VC2008 y VC6. Funciona bien para ambos.

+1

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

+0

Por cierto, su función 'get' se puede simplificar a: std :: string get () {return "Hello World"; } – fredoverflow

Respuesta

10

Ver this question. El estándar garantiza que un temporal vive hasta el final de la expresión de la cual es parte. Como toda la invocación de función es la expresión, se garantiza que el temporal persistirá hasta después del final de la expresión de invocación de función de la que forma parte.

Cuestiones relacionadas