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

梦想的初衷 提交于 2019-12-04 05:31:30

问题


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 ?


回答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 ?

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*




回答2:


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.




回答3:


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:


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.



来源:https://stackoverflow.com/questions/19244331/stdstring-c-str-scope-after-returning-from-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!