Vectors of unique pointer


#1

Hello, I want to have a container of an abstract class that simply has 3 methods, draw(), setup() and update(). I have heard that the only way to do it in c++ is to use unique_ptr or shared_ptr. I am doing it like this, this is my abstract class:

#pragma once

class ILayer {
public:
    virtual void setup() = 0;
    virtual void update() = 0;
    virtual void draw() = 0;
};

This is an implementation of the abstract class:

#include "ofxLathePrimitive.h"
#include "ILayer.h"

class LatheFlower : public ILayer{
public:
    ofxLathePrimitive lathe;

    virtual void setup(){
        lathe.build();
    }

    virtual void update(){
        lathe.update();
    }

    virtual void draw(){
        lathe.draw();
    }
};

I want to fill out a vector of ILayer, defined as:

std::vector<std::unique_ptr<ILayer>> layers;

And I am placing element to it like this:

    std::unique_ptr<ILayer> lathe = std::make_unique<LatheFlower>();
    layers.push_back(lathe);
    for(auto &l : layers){
        l->setup();
    }

But I am receving this error:

What am I doing wrong?


#2

you can’t use push_back with unique_ptr cause push_back copies what you pass and by definition a unique_ptr can’t be copied because it’s unique so there can only be one copy of it at any time.

What you can do is move it into the vector so the original is no longer valid using std::move:

auto lathe = std::make_unique<LatheFlower>();
layers.push_back(std::move(lathe));

#3

This worked, thanks!


#4

By the way, I came across this article https://jonasdevlieghere.com/containers-of-unique-pointers/ that could be interesting is someone else is going to use a vector of unique pointers.