Vectors of unique pointer

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 {
    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{
    ofxLathePrimitive lathe;

    virtual void setup(){;

    virtual void update(){

    virtual void 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>();
    for(auto &l : layers){

But I am receving this error:

What am I doing wrong?

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>();
1 Like

This worked, thanks!

By the way, I came across this article that could be interesting is someone else is going to use a vector of unique pointers.

1 Like