Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good practice or convention for cleanup heap allocated object?

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?

like image 919
eonil Avatar asked Feb 17 '23 09:02

eonil


2 Answers

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.

like image 169
Reed Copsey Avatar answered Mar 23 '23 18:03

Reed Copsey


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.

like image 23
Slava Avatar answered Mar 23 '23 17:03

Slava