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

2020-04-21 02:02发布

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 ?

4条回答
够拽才男人
2楼-- · 2020-04-21 02:15

Ad.1) - You are not returning a char pointer, you are returning an instance of CString implicitly constructed from that pointer. CString takes a copy of passed character data.

Ad.2) - Copying or assigning a CString creates a deep copy.

查看更多
Evening l夕情丶
3楼-- · 2020-04-21 02:22

Yes, the memory is safely copied into the Cstring object returned from the function. It is a deep copy. Even the documentation says so:

Because the constructors copy the input data into new allocated storage, you should be aware that memory exceptions may result.

查看更多
何必那么认真
4楼-- · 2020-04-21 02:22

1.): The lifetime of the char const * returned by c_str() is only as long as the control flow is inside the function StringFunc, since the string variable abc will be destroyed at the end of that function. However, since you return a CString by value, a temporary is implicitly constructed from the result of c_str(), and that CString is returned; this temporary return value in turn is valid until the end of the expression that the function call appears in (i.e. the whole statement where you assign the result of function StringFunc to temp). The result from your StringFunc is therefore safely copied into your Temp variable in main.

2.) It's a "deep" copy, you construct a new object there! Since you return by value, your compiler will by most probability actually avoid copying anything (see Return-Value optimization) and will instead simply construct the one object.

查看更多
Fickle 薄情
5楼-- · 2020-04-21 02:27

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*

查看更多
登录 后发表回答