1

I'm trying to compile the following code but I get this error:

error: no viable conversion from 'unique_ptr' to 'unique_ptr'

What I'm trying to do is create a smart pointer that wraps some objects and then use them as listeners.

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

class Table {

  public:
    struct Listener{ 
      virtual void handle(int i) = 0;
    };

    std::vector<std::unique_ptr<Listener>> listeners_;

    void add_listener(std::unique_ptr<Listener> l){
      listeners_.push_back(l);
    }

};


struct EventListener: public Table::Listener {
  void handle(int e){  
    std::cout << "Something happened! " << e << " \n";
  }
};

int main(int argc, char** argv)
{
  Table table;
  std::unique_ptr<EventListener> el;
  table.add_listener(el);

  return 0;
}

Any ideas will be appreciate!

oscarm
  • 2,630
  • 6
  • 41
  • 74

2 Answers2

2

std::unique_ptr cannot be copied, only moved : you can use std::move :

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

class Table {

  public:
    struct Listener{ 
      virtual void handle(int i) = 0;
    };

    std::vector<std::unique_ptr<Listener>> listeners_;

    void add_listener(std::unique_ptr<Listener> l){
      listeners_.push_back(std::move(l));
    }

};


struct EventListener: public Table::Listener {
  void handle(int e){  
    std::cout << "Something happened! " << e << " \n";
  }
};

int main(int argc, char** argv)
{
  Table table;
  std::unique_ptr<EventListener> el;
  table.add_listener(std::move(el));

  return 0;
}

Live demo

quantdev
  • 23,517
  • 5
  • 55
  • 88
0

There is no copy constructor for unique_ptr

From cppreference.com:

"Copy construction is disabled for objects of type unique_ptr (see move constructors, 6 and 7)."

You have to move it explicitly, or extract raw pointer and copy it around

Severin Pappadeux
  • 18,636
  • 3
  • 38
  • 64