Search code examples
c++boostshared-ptr

Can I create a boost::shared_ptr to a local variable?


I have some methods that take a reference to a given object, and some are taking boost::shared_ptr. So far in my test method I created a shared_ptr pointing to one of these objects and pass *ptr to the methods expecting a reference. Is it possible to do it the other way round, e.g. create a local object on the stack, and then create a shared pointer to it in a safe way, to arrive at the straightforward alternative to &obj operator with traditional pointers?


Solution

  • #include <boost/shared_ptr.hpp>
    
    void null_deleter(int *)
    {}
    
    int main()
    {
        int i = 0;
        boost::shared_ptr<int> p(&i, &null_deleter);
    }