I am learning pointers in c++ and am having some trouble.
I have a class Foo that in the header file declares some data:
private:
const Bar *obj;
Where Bar is a class.
Then in the c++ implementation I want to replace *obj so that it points to a completely different Bar object. *obj is constant, so how do I change what is in what *obj points to or rather, what is in memory at *obj? Also in Foo‘s destructor, how do I deallocate *obj?
Given your class definition
objis a pointer to a constantBarobject. You can change what that pointer points to, but you cannot change the contents of the object pointed to.So, if you have a new
Barobject and you’d like to changeobjso it points to that, you can simply assign the new value:There are two issues, however.
If the new
Barobject is created outside the class, you cannot directly assign it toobjbecause the latter is private. Hence you need a setter function:You must determine who will eventually own the
Barobject, i.e. who is responsible for freeing the heap space it takes. If the caller is responsible then you can code it as above, i.e.class Awill never create newBarobjects, nor delete any. It will just maintain a pointer toBarobjects created and deleted outside the class.But if
class Aabove is actually responsible for the memory space taken by theBarobjects, you must usedelete objin the destructor to free the space, and you must also free the space when you get a newBarobject assigned. That is, theset_objfunction above needs to be changed to this:Otherwise you’ll have a memory leak. Similar measures must be taken in the copy constructor (unless you delete it), as well as the assignment operator: Both functions are used whenever a copy of a
class Aobject is made, and in that case you must make sure that you do not simply copy the pointer, but instead allocate fresh space and copy the object (i.e. you must perform a deep copy):Having said this, if your class is responsible for the memory space, it is a much better idea to use a smart pointer class instead of a raw pointer. The main reasons are: (i) The above is quite complicated and it’s easy to make mistakes; (ii) The above is still not very good – there may still be memory leaks or worse problems when an exception is thrown, e.g. in the constructor of
Bar. C++11 provides a smart pointer class calledstd::unique_ptr, which seems ideal for your purposes:With this in place, the smart pointer will take care of any memory space that needs to be freed automatically, both at destruction time as well as when a new
Barobject is assigned to the pointer.