So I have the standard C++ setup with an object that stores another object. The stored object is owned completely, it’s never leaked to the outside. The member is non-const.
class Container
{
private:
Contained item;
}
As I understand, when my Container is instantiated the default constructor will be called on the item member and I don’t have to manage it in the initializer list.
Also do I understand it correctly that when my object is destroyed the dtor on the item will be called automatically?
Another option would be to store it by reference of course
class Container
{
private:
Contained& item;
public:
Container() : Contained()
{
}
}
in which case I don’t know whether I should delete it in the dtor.
Yet another option is to store it by ptr
class Container
{
private:
Contained* item;
public:
Container()
{
item = new Contained();
}
~Container()
{
delete item;
}
}
Knowing that my item never gets returned to the caller and never bleeds into the outside API and never gets reassigned, what is the best way to proceed? As I mentioned, the item member is not const
(it will be a self-resizing data structure).
The easiest is to store the object itself. Using reference for this purpose is, I would say, confusing. One advantage with using the pointer is that you then may be able to avoid defining the Contained type in the header file – you can instead forward declare Contained, and keep all the details inside the .cpp file.