views:

123

answers:

2

Suppose I have a class Boda:

class Boda {
    ...
};

And I have a member cydo in this class that I want to be a smart pointer (that is, I want it to get deallocated automatically as soon as the class gets destroyed).

I am using Boost's smart pointers, so I write:

class Boda {
    boost::shared_ptr<int> cydo;
    public:
        Boda () {
            cydo = boost::shared_ptr<int>(new int(5));
        }
};

Is this the correct use of putting smart pointers as class members?

Thanks, Boda Cydo.

+10  A: 
class Boda {
    boost::shared_ptr<int> cydo;
    public:
        Boda () : cydo(new int(5)) {} 
};

Though, I can't think why you'd want to wrap an int ... :)

dirkgently
Oops, that was only an example. I really have something better there. :)
bodacydo
Try to always 1) use initializer lists and 2) use direct initialization rather than copy initialization. Avoid redundant assignments and copies. See Sutter: http://www.gotw.ca/gotw/036.htm
dirkgently
+1  A: 

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.

David Rodríguez - dribeas