我有以下設定:
海報.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);
}
};
...
然后在 main.cpp 我有以下
void output(int x)
{
std::cout << x;
}
int main()
{
Poster<int> p;
int x = 5;
p.post(output, x);
}
每次我嘗試構建它時,我都會得到:
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
我不確定這是為什么。任何幫助將不勝感激。
uj5u.com熱心網友回復:
在post2(),你unique_ptr<Poster<T>> 按值取值。僅當您向其傳遞右值參考(“臨時”或 中的某些內容std::move())時,這才有效。
從您的示例來看,您是否真的需要內部唯一的所有權post2()(通常不是,但在函式中)并不明顯。如果您不需要所有權,您可以使用unique_ptr<Poster<T>>& p,甚至只是Poster<T>& p. 如果您想轉讓所有權并因此testPtr被清空,您可以寫入post():post2(std::move(testPtr2), ...);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/515299.html
標籤:C 代码唯一的-ptr
上一篇:輸出沒有回圈和陣列的最小和最大數
下一篇:指標作為函式指標中的引數
