开发者

What is the right way to put a smart pointer in class data (as class member) in C++?

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 o开发者_运维知识库f putting smart pointers as class members?

Thanks, Boda Cydo.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜