【问题标题】:Tring to create a unique pointer gives me an error [duplicate]尝试创建唯一指针给我一个错误[重复]
【发布时间】:2021-07-30 06:10:52
【问题描述】:

我有一个带有以下构造函数的 Boid 类

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

我需要创建一个由 Boid 对象的唯一指针组成的向量。按照在线示例,我尝试执行以下操作

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);
}

它给了我以下错误。

    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

我真的无法弄清楚我做错了什么,所以任何帮助都将不胜感激。谢谢。如果需要更多信息,请告诉我。

【问题讨论】:

    标签: c++ unique-ptr


    【解决方案1】:

    std::unique_ptr 不能复制,它没有复制构造函数但有移动构造函数。您可以使用std::moveboid 转换为右值,然后可以使用移动构造函数。

    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));
    

    或者直接传临时(也是右值)。

    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)
        ));
    

    【讨论】:

      猜你喜欢
      • 2023-04-06
      • 1970-01-01
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多