简体   繁体   English

使用unique_ptr进行投放的正确方法

[英]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' 错误:没有从“ unique_ptr”到“ 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 : std::unique_ptr不能复制,只能移动:您可以使用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 没有用于unique_ptr的副本构造函数

From cppreference.com: 从cppreference.com:

"Copy construction is disabled for objects of type unique_ptr (see move constructors, 6 and 7)." “为unique_ptr类型的对象禁用了复制构造(请参阅移动构造函数6和7)。”

You have to move it explicitly, or extract raw pointer and copy it around 您必须显式移动它,或提取原始指针并在周围复制它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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