Search code examples
c++boostshared-ptr

how to overcome make_shared constness


I'm faced with a problem, and can't decide what the correct solution is.

Here is the code example for illustration:

#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>

class TestClass{
    public:
        int a;
        TestClass(int& a,int b){};
    private:
        TestClass();
        TestClass(const TestClass& rhs);
};

int main(){
    int c=4;
    boost::shared_ptr<TestClass> ptr;

//NOTE:two step initialization of shared ptr    

//     ptr=boost::make_shared<TestClass>(c,c);// <--- Here is the problem
    ptr=boost::shared_ptr<TestClass>(new TestClass(c,c));

}

The problem is I can't create a shared_ptr instance because of make_shared gets and passes down arguments to TestClass constructor as const A1&, const A2&,... as documented:

template<typename T, typename Arg1, typename Arg2 >
    shared_ptr<T> make_shared( Arg1 const & arg1, Arg2 const & arg2 );

I can trick it with boost::shared(new ...) or rewrite the constructor for const references, but that doesn't seem like the right solution.

Thank you in advance!


Solution

  • You can use boost::ref to wrap the argument up, ie:

    ptr = boost::make_shared< TestClass >( boost::ref( c ), c );