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 ?

有帮助吗?

解决方案

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*

其他提示

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.

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.

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top