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

उत्पादन का जीवन स्कोप है:अस्थायी चर

--> 
--> Hello World 

हैलो, मैं पता हो सकता है सही व्यवहार सी ++ मानक द्वारा गारंटी है, या यह अपने संकलक विक्रेता कार्यान्वयन पर निर्भर करता है? मैंने इसका परीक्षण वीसी -2008 और वीसी 6 के तहत किया है। दोनों के लिए ठीक काम करता है।

+1

डुप्लिकेट: http://stackoverflow.com/questions/2506793/c-life-span-of- समकालीन-arguments –

+0

वैसे, आपके 'get' फ़ंक्शन को सरलीकृत किया जा सकता है: std :: string get () {वापसी "हैलो वर्ल्ड"; } – fredoverflow

उत्तर

10

this question देखें। मानक गारंटी देता है कि अभिव्यक्ति के अंत तक एक अस्थायी जीवन जिसमें यह एक हिस्सा है। चूंकि संपूर्ण फ़ंक्शन आमंत्रण अभिव्यक्ति है, अस्थायी को फ़ंक्शन आमंत्रण अभिव्यक्ति के अंत के बाद तक जारी रखने की गारंटी दी जाती है जिसमें यह एक हिस्सा है।

संबंधित मुद्दे