[英]What is the correct way to convert a std::unique_ptr to a std::unique_ptr to a superclass?
[英]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.