The real question you should ask yourself is whether you need to allocate the member separately from the class. It is usually better if you just store the member in the class --as compared to storing any type of pointer. If you cannot do it, if for example the lifetime of the member starts before or after the container is created, can be extended beyond of ownership of the member can be yield to other objects, then you must use pointers.
Once you need to use pointers, you should prefer smart pointers to raw pointers, and select the particular type based on your requirements. If the member ownership is not to be shared with other objects, but you need to use a pointer because the lifetime of the contained object may start before or after that of the container, or if ownership can be transferred to other objects, but management of the resource (unless yielded) is the sole responsibility of the container, then prefer unique_ptr
or auto_ptr
.
If the contained object does not belong solely to this class then use a shared_ptr
. This can also be used if the member is used by different threads, with each thread holding its own shared_ptr
even if the ownership is held in only one of the threads, to avoid destroying the object in one thread when it is still being used in another.