Question

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.

Was it helpful?

Solution

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 ... :)

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top