Search code examples
c++shared-ptrsmart-pointersclass-members

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 of putting smart pointers as class members?

Thanks, Boda Cydo.


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