I have the following set up:
poster.h
template<class T>
class Poster
{
private:
unique_ptr<Poster<T>> testPtr = nullptr;
public:
void post(void (*callback_function)(T), T data)
{
post2(testPtr, callback_function, data);
}
void post2(unique_ptr<Poster<T>> p, void (*callback_function)(T), T data)
{
callback_function(data);
}
};
...
Then in main.cpp i have the following
void output(int x)
{
std::cout << x;
}
int main()
{
Poster<int> p;
int x = 5;
p.post(output, x);
}
Every time i try to build this i get:
Severity Code Description Project File Line Suppression State
Error C2280 'std::unique_ptr<Poster<int>,std::default_delete<Poster<int>>>::unique_ptr(const std::unique_ptr<Poster<int>,std::default_delete<Poster<int>>> &)': attempting to reference a deleted function
I am not sure why this is. Any help would be greatly appreciated.
CodePudding user response:
In post2()
, you take unique_ptr<Poster<T>>
by value. That only works if you pass it an rvalue reference ('temporary', or something in std::move()
).
From your example it's not apparent if you really need unique ownership inside post2()
(not generally, but in the function). If you don't need ownership, you might take unique_ptr<Poster<T>>& p
, or even simply just Poster<T>& p
. If you want ownership to be transferred, and thus testPtr
to be emptied, you can write in post()
: post2(std::move(testPtr2), ...);