[英]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.