【问题标题】:Correct way to cast using unique_ptr使用 unique_ptr 进行投射的正确方法
【发布时间】:2014-11-28 02:59:52
【问题描述】:

我正在尝试编译以下代码,但出现此错误:

错误:没有从 'unique_ptr' 到 'unique_ptr' 的可行转换

我想做的是创建一个智能指针来包装一些对象,然后将它们用作侦听器。

#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;
}

任何想法将不胜感激!

【问题讨论】:

标签: c++ smart-pointers


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    unique_ptr 没有复制构造函数

    来自 cppreference.com:

    “对 unique_ptr 类型的对象禁用复制构造(参见移动构造函数,6 和 7)。”

    你必须明确地移动它,或者提取原始指针并复制它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多