Search code examples
c++shared-ptr

Error 2664 - Can't convert from std::vector<...> to std::tr1::shared_ptr


Need help with an error message that I just can't figure out. I am getting the following:

Error   1   error C2664: 'void std::vector<_Ty>::push_back(_Ty &&)' : cannot convert parameter 1 from 'Physics::Box2D' to 'std::tr1::shared_ptr<_Ty> &&'    d:\visual studio 2010\projects\c++\test001\main.cpp 31  1   Test001

Not sure why, the code should work. I found sample code on StackOverFlow.com Maybe I am missing something.

Please help...newbie boost library user

//this code works fine...
Box2D *b = new Box2D();
b->Info();

//but this code fails...
vector< shared_ptr<Box2D> > boxes;
boxes.push_back( new Box2D() );  <--error happens here

Solution

  • The constructor for std::shared_ptr<T> taking a pointer to T is explicit, i.e. you can't implicitly convert to this type. Also, the error message doesn't seem to match the code. However, try this:

    boxes.push_back(std::shared_ptr<Box2D>(new Box2D()));
    

    ... or

    boxes.push_back(std::make_shared<Box2D>());