Behemyth
Behemyth

Reputation: 305

Adding a Newly Created Object to a Vector

I recently stated using pointers in a program and when I try the following, I am given this error.

stored_points.push_back(new Point(anchor_y,anchor_x,last_direction));   

error C2664: 'void std::vector<_Ty>::push_back(_Ty &&)' : cannot convert parameter 1 from 'Point *' to 'Point &&' with[ _Ty=Point ] Reason: cannot convert from 'Point *' to 'Point' No constructor could take the source type, or constructor overload resolution was ambiguous

I understand that using new gives a pointer back and that .push_back can't accept that, however, I have no idea on how to go about fixing that.

Upvotes: 0

Views: 106

Answers (2)

Yang Chi
Yang Chi

Reputation: 432

A very quick work-around would be change the definition of your vector. Instead of vector<Point>, change it to vector<Point *>.

But you should seriously consider using smart pointer in such situation. So vector<shared_ptr<Point> > is what you may want to consider.

Smart pointer is available in Boost and TR1.

Upvotes: 0

wquist
wquist

Reputation: 2607

How are you defining your vector? If its vector<Point>, try changing it to vector<Point*>. This tells the vector to store pointers to the objects instead.

Upvotes: 0

Related Questions