根據檔案,它說
我們已經在 return 陳述句中對區域值和函式引數進行了隱式移動。以下代碼編譯得很好:
std::unique_ptr<T> f(std::unique_ptr<T> ptr) { return ptr; }但是,以下代碼無法編譯
std::unique_ptr<T> f(std::unique_ptr<T> && ptr) { return ptr; }相反,您必須鍵入
std::unique_ptr<T> f(std::unique_ptr<T> && ptr) { return std::move(ptr); }
以下是我的問題:
1.確實沒有復制ctor std::unique_ptr<T>,不應該有一個函式可以接受宣告為的引數std::unique_ptr<T>。請參閱此代碼片段,它不會編譯。
#include <memory>
class FooImage{};
std::unique_ptr<FooImage> FoolFunc(std::unique_ptr<FooImage> foo)
{
return foo;
}
int main()
{
std::unique_ptr<FooImage> uniq_ptr(new FooImage);
FoolFunc(uniq_ptr);
}
2.為什么
std::unique_ptr<T> f(std::unique_ptr<T> && ptr) {
return ptr;
}
不編譯?
有人可以對此事有所了解嗎?
uj5u.com熱心網友回復:
1.確實沒有復制ctor
std::unique_ptr<T>,不應該有一個函式可以接受宣告為的引數std::unique_ptr<T>。
其實只要把原圖移到std::unique_ptr這個本地引數就可以了
FoolFunc(std::move(uniq_ptr)); // ok
FoolFunc(std::unique_ptr<FooImage>{new FooImage}); // also ok
2.為什么
std::unique_ptr<T> f(std::unique_ptr<T> && ptr) { return ptr; }不編譯?
的型別雖然ptr是右值參考,但它本身就是左值,所以return ptr會呼叫copy ctor,需要再次std::move轉換ptr為右值
std::unique_ptr<T> f(std::unique_ptr<T> && ptr) {
return std::move(ptr);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/440817.html
上一篇:每秒函式呼叫控制率
下一篇:C 用默認值初始化陣列類
