簡體   English   中英

使用unique_ptr進行投放的正確方法

[英]Correct way to cast using unique_ptr

我正在嘗試編譯以下代碼,但出現此錯誤:

錯誤:沒有從“ 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;
}

任何想法將不勝感激!

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

現場演示

沒有用於unique_ptr的副本構造函數

從cppreference.com:

“為unique_ptr類型的對象禁用了復制構造(請參閱移動構造函數6和7)。”

您必須顯式移動它,或提取原始指針並在周圍復制它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM