Search code examples
c++c++11vectorunique-ptrraii

How to add objects to a std::vector<unique_ptr<obj>>?


Question:
How to add objects to a std::vector<unique_ptr<obj>>?

I have a class, and this is what I am trying to do...
Below, I'm trying to use std::unique_ptr<Ball> in my vector, as I thought it would be the easiest.

class Ball {
public:
    Ball(float x, float y);
    std::vector<std::unique_ptr<Ball>> object;
    // other declarations below...
};


Here I am trying to push_back new elements:

Ball ball { 0, 0 };
for (size_t i { 0 }; i != 50; ++i) {
ball.object.push_back(new Ball { 0, 0 });
//        ^ here is the error
}

And I do no understand the error I'm getting.
Error:
error C2664: 'void std::vector<std::unique_ptr<Ball,std::default_delete<_Ty>>,std::allocator<std::unique_ptr<_Ty,std::default_delete<_Ty>>>>::push_back(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : cannot convert argument 1 from 'Ball *' to 'std::unique_ptr<Ball,std::default_delete<_Ty>> &&'


Solution

  • When you use push_back, you need to create a unique_ptr. Since that's too much typing and error-prone, you can use emplace_back instead to forward your ball object. In C++14, make_unique is available and should be preferred.

    for (size_t i { 0 }; i != 50; ++i) {
        ball.balls.emplace_back(new Ball { 0, 0 });
    }