Read-write object with member pointer and memory management

Hi, I have an object which I write on a ROOT file and then read back. It contains a pointer to another object, so it looks a bit like this:

#include "Contained.h"

class Container: public TObject{
public:
	Container();
	~Container();

	Contained *contained;
	
ClassDef(Container,1)
}

When I use it to write on a ROOT file I have to create the contained object, which I destroy at the end of the container’s life:

#include "Container.h"

Container::Container(){
	contained = new Contained;
}

Container::~Container(){
	delete contained;
}

So far so good, in my write program I create a Container, fill the Contained, write on file and destroy the Container so no memory is leaked.

When I write a read program I create a Container object in memory and then set the branch address for the Container object on file. What happens now?
[ul]
[li]Does the Container streamer allocate again a Contained (thus generating a memory leak from the allocation in constructor) or does it use the Contained allocated in the constructor? [/li]
[li]What would happen if the contained pointer is NULL (e.g. because I modify the constructor so that no allocation is done): would ROOT automatically allocate the memory for contained when reading from file? If so, who owns the allocated contained (ROOT or Container)? [/li][/ul]
Thanks for the help.

[quote]Does the Container streamer allocate again a Contained (thus generating a memory leak from the allocation in constructor) [/quote]Since the pointee ‘might’ not be of the right type, the I/O layer will delete the object and allocate a new one (so no memory leak).

If you want this behavior you can use the add the marker → as a comment to the data member.

Contained *contained; //-> This will tell the I/O layer that it can assume contained will never be nullptr (i.e. it is allocated in the constructor) and it will always be the same type.

[quote]What would happen if the contained pointer is NULL (e.g. because I modify the constructor so that no allocation is done): would ROOT automatically allocate the memory for contained when reading from file? If so, who owns the allocated contained (ROOT or Container)? [/quote]If the pointer is initialized to nullptr in the constructor, the I/O layer will indeed allocate an object as needed, the containing object (i.e. of type Container here) remains the owner of the pointee.

Cheers,
Philippe.

Thanks Philippe, very exhaustive and clear!!