1

I have a Boid class with the following constructor

Boid(olc::vf2d _position, float _angle, olc::Pixel _color) : position(_position), rotationAngle(_angle), color(_color)
    {
    };

I need to create a vector of unique pointers of Boid objects. Following online examples, I tried to do the following

std::vector<std::unique_ptr<Boid>> boids;
for (int i = 0; i < nInitialBoids; i++)
{
    std::unique_ptr<Boid> boid = std::make_unique<Boid>
        (
        olc::vf2d(rand() % 600 * 1.0f, rand() % 300 * 1.0f),
        rand() % 7 * 1.0f,
        olc::Pixel(0, 0, (rand() % 150) + 100)
        );
    boids.push_back(boid);
}

It gives me the following error.

    Severity    Code    Description Project File    Line    Suppression State
    Error   C2280   'std::unique_ptr<Boid,std::default_delete<Boid>>::unique_ptr
    (const std::unique_ptr<Boid,std::default_delete<Boid>> &)': attempting to reference 
    a deleted function  boids   C:\Program Files (x86)\Microsoft Visual 
    Studio\2019\Community\VC\Tools\MSVC\14.28.29333\include\xmemory 701

I really cannot figure out what I am doing wrong, so any help would be appreciated. Thanks. Please let me know if more information is needed.

Apple_Banana
  • 131
  • 6

1 Answers1

1

std::unique_ptr can't be copied, it doesn't have copy-constructor but has move constructor. You can use std::move to convert boid to rvalue then the move constructor could be used.

std::unique_ptr<Boid> boid = std::make_unique<Boid>
    (
    olc::vf2d(rand() % 600 * 1.0f, rand() % 300 * 1.0f),
    rand() % 7 * 1.0f,
    olc::Pixel(0, 0, (rand() % 150) + 100)
    );
boids.push_back(std::move(boid));

Or pass the tempoary (which is also rvalue) directly.

boids.push_back(std::make_unique<Boid>
    (
    olc::vf2d(rand() % 600 * 1.0f, rand() % 300 * 1.0f),
    rand() % 7 * 1.0f,
    olc::Pixel(0, 0, (rand() % 150) + 100)
    ));
songyuanyao
  • 169,198
  • 16
  • 310
  • 405