简体   繁体   中英

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM