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 ?
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:1.): The lifetime of the
char const *
returned byc_str()
is only as long as the control flow is inside the functionStringFunc
, since the string variableabc
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 ofc_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 functionStringFunc
to temp). The result from yourStringFunc
is therefore safely copied into yourTemp
variable inmain
.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.
abc
will be valid untilStringFunc() 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:It's deep copy. it constructs a new
CString
object fromconst char*