I am learning C++. I have C, C#, ObjC background. Pretty higher level languages.
On C# or ObjC , it's trivial returning heap allocated object as a result of a function or method. Because the cleanup of objects are managed (by convention). It will be destroyed at proper time.
But I don't know how should I handle this in C++.
For example,
std::string* makeString()
{
std::string* str = GetSomeStringFromArbitrarySource ();
SaveSomewhereElseInternally (str);
return str;
}
void useString ()
{
std::string* str = makeString ();
// Where and how should I cleanup the `str` object?
// It is not safe `delete str` here because it may be used on another place.
}
What is the recommended and conventional way to cleanup heap allocated object when it is passed over many functions?
I looked several smart pointers, but they don't look really reduce complexity or things to care. Am I misunderstanding the smart pointers?
I looked several smart pointers, but they don't look really reduce complexity or things to care. Am I misunderstanding the smart pointers?
Most likely, yes. In C++, since you have to handle this yourself (no GC will clean it up for you), you need a way to track the usage of each and every object.
You can manually match every new
with a delete
, but this is sometimes difficult or impossible, such as in your scenario above. There is no way to know whether the object is being used elsewhere.
Smart pointers solve this by managing the lifetime for you, so you don't need to delete. They use various mechanisms to track how many places the object is being used, and call delete
when the last one is done.
That being said, there isn't much reason in this specific case to use pointers at all. If you're working with std::string
, you can pass the string around by value and it will never be an issue.
You are misunderstanding the smart pointers most probably by the same reason why you wrote:
std::string* makeString()
Instead of what most C++ programmers would write instead:
std::string makeString()
You would need to better understand object lifetime in C++ and then smart pointers concept would be much easier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With