oscarm
oscarm

Reputation: 2650

Correct way to cast using unique_ptr

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!

Upvotes: 1

Views: 2829

Answers (2)

Severin Pappadeux
Severin Pappadeux

Reputation: 20080

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

Upvotes: 0

quantdev
quantdev

Reputation: 23803

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

Upvotes: 2

Related Questions