Search code examples
c++visual-studio-2010visual-c++mfcobject-lifetime

std::string c_str() scope after returning from function


I have below mentioned function in C++/MFC:

CString StringFunc()
{
    std::string abc = "Hello";

    return abc.c_str();

}

int main()
{
    CString Temp = StringFunc();

    Use_Temp(Temp);
}

1.) What would be the lifetime of abc.c_str() pointer returned by StringFunc(), would it be safely copied to variable 'Temp' after StringFunc() returns ?

2.) CString Temp = StringFunc() is a Shallow copy operation or Deep Copying ?


Solution

  • What would be the lifetime of abc.c_str() pointer returned by StringFunc(), would it be safely copied to variable 'Temp' after StringFunc() returns ?

    abc will be valid until StringFunc() function returns. Yes, it's safe to return a copy to CString.

    If you return a pointer to std::string::c_str() then it's dangerous, for example:

    const char* EvilFunc()  // bad, dont' do it
    {
       std::string abc = "Hello";
       return abc.c_str();
    }
    
    const char* p = EvilFunc(); // p becomes wild pointer when EvilFunc returns
    

    CString Temp = StringFunc() is a Shallow copy operation or Deep Copying ?

    It's deep copy. it constructs a new CString object from const char*