5

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!

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
sohel
  • 377
  • 3
  • 13
  • possible duplicate of [boost make\_shared takes in a const reference. Any way to get around this?](http://stackoverflow.com/questions/1373896/boost-make-shared-takes-in-a-const-reference-any-way-to-get-around-this) – BenC May 05 '14 at 16:07

1 Answers1

11

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

ptr = boost::make_shared< TestClass >( boost::ref( c ), c );
Ylisar
  • 4,293
  • 21
  • 27