Serious question.
Does this leak? I obviously can't delete some_string from within this function.Code:string createString() { string some_string = "string"; return some_string; }
Serious question.
Does this leak? I obviously can't delete some_string from within this function.Code:string createString() { string some_string = "string"; return some_string; }
No, not in this context. You're actually returning a copy of the string object.
There is no call to new, so there doesn't need to be any call to delete.
Returning a string that's allocated on the stack in a function is undefined behavior. You might be able to use it, but it's not safe.
Declare a pointer in the function and allocate memory with new, and return the point. That way, it's allocated on the heap.
"What's up, Doc?"
"'Up' is a relative concept. It has no intrinsic value."
>> Returning a string that's allocated on the stack in a function is undefined behavior. You might be able to use it, but it's not safe.
This is wrong (at least in the context of the thread). The OP's code is safe and good. It is also better than returning something allocated on the heap.
A C++ string is an object that will be properly copied and destroyed as appropriate when you return a string object from the function.
Ah, sorry. My bad. More of a C programmer than a C++ programmer, I didn't think the object would be copied.
But you can't deny that it's slower to return a copy of the object than to return a pointer to it, but the difference is negligible unless the function is called often.
"What's up, Doc?"
"'Up' is a relative concept. It has no intrinsic value."
IceDane's concern would apply if one returned a reference instead of a copy.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
>> But you can't deny that it's slower to return a copy of the object than to return a pointer to it,
>> but the difference is negligible unless the function is called often.
It's probably slower to return a copy of the string than a pointer, true, but there are a couple other things to remember about that. RVO will often skip the copy there, easing any performance hit. Also, if you return a pointer to dynamically allocated memory, the slowdown from that versus local stack variables might be a greater issue.
In the end, it will rarely be a problem, so the clarity of returning the copy usually makes sense, IMO.
And if you really that concerned about performance (which would only be applicable if this function is called several million times in a row), you could use a reference:
Code:void GetString( std::string& output ) { output = "Hello World"; }