Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with pointers without smart pointers?

Tags:

c++

pointers

I'm reading C++ Primer Plus by Stephen Frata. I've read up to chapter 6, which means I learned about pointers but not about objects and classes (Although I know about OOP).

I came from a ActionScript (Flash) and Java background, so I never dealt with pointers before, but I understand them. I have a bunch of questions about them though.

As I understood, you need to pair new and delete, i.e. the object/function that creates a pointer is responsible for freeing it. But imagine a simple factory function, like this :

SomeObject * createSomeObject(){
    return new SomeObject;
}

That looks pretty problematic. Who is responsible for freeing this pointer now?

What if I create a class that gives public access to a pointer that it created. Following the new/delete rule, this class should be responsible for freeing the pointer in its destructor. But since the pointer might be used by another class, destroying the first class would breaks the second...

Those two interrogations are similar. What can I do to manage a pointer that is known to other entities than the one who created it?

Note : I'm aware that smart pointer could solve this problem, but I'm wondering how people do without them.

like image 609
subb Avatar asked Feb 25 '23 07:02

subb


1 Answers

"Who is responsible for deleting it?" is a very good question. Generally with a function like that, you would simply document that the returned pointer must be deleted. It is up to the user of the factory to determine which class or function is responsible. However, this is a bit vague, and is indeed a problem.

In modern C++ style, this is exactly why smart pointers are used. Consider:

std::unique_ptr<SomeObject> createSomeObject() {
    return new SomeObject;
}

In this case, the pointer is owned by the returned unique_ptr. Wherever you move it, the stored pointer is deleted in its destructor (when it scopes out or when the object containing it destructs). This makes obvious which part of the code is responsible for destroying it and the delete happens automatically (so you can't forget to delete it or make some "destroy" call), so is considered the solution to the above problem.

like image 84
AshleysBrain Avatar answered Mar 04 '23 09:03

AshleysBrain