Reputation: 2650
I'm trying to compile the following code but I get this error:
error: no viable conversion from 'unique_ptr' to '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!
Upvotes: 1
Views: 2829
Reputation: 20080
There is no copy constructor for unique_ptr
From cppreference.com:
"Copy construction is disabled for objects of type unique_ptr (see move constructors, 6 and 7)."
You have to move it explicitly, or extract raw pointer and copy it around
Upvotes: 0
Reputation: 23803
std::unique_ptr
cannot be copied, only moved : you can use 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;
}
Upvotes: 2