1

I believe I know why this is happening, but being new to c++ I'm unsure what the correct way to handle it is (without using raw pointers). From my research what is happening is that when I attempt to push_back a Stage object into a vector a copy is being attempted and since Stage contains unique_ptr members which have deleted copy constructors, the below error is encountered.

Is my understanding correct? If so, what is the best way to resolve this issue in modern c++?

Minimal Reproducible Example

#include <iostream>
#include <vector>
#include <memory>

class Actor
{
private:
    int prop1 = 1;
    int prop2 = 2;
public:
    Actor() {}
};

class Stage
{
public:
    Stage() {}
    std::vector<std::unique_ptr<Actor>> actors;
};

class App
{
public:
    App() {}
    std::vector<Stage> stages;
};

int main()
{
    auto act1 = std::make_unique<Actor>();

    auto sta1 = Stage();
    sta1.actors.push_back(std::move(act1));

    auto app = App();
    app.stages.push_back(sta1); // Issue occurs when copying Stage object into vector since Stage object contains members of type unique_ptr (or at least that's my best guess from the research I have done)

    std::cin.get();
    return 0;
}

Compiler Error from MSVC

Error   C2280   'std::unique_ptr<Actor,std::default_delete<_Ty>>::unique_ptr(
const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to 
reference a deleted function    SmartPointers   
c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.12.25827\include\xmemory0    945 
whitwhoa
  • 2,389
  • 4
  • 30
  • 61

1 Answers1

3

unique_ptr cannot be copied, only moved. That's why it's called unique in the first place.

You used the right approach when pushing to actors so you only need to adapt it to stages.

 app.stages.push_back(std::move(sta1));
pablo285
  • 2,460
  • 4
  • 14
  • 38