簡體   English   中英

關於從 function 返回 unique_ptr 的問題

[英]Question about returning an unique_ptr from a function

根據文檔,它說

我們已經在 return 語句中對局部值和 function 參數進行了隱式移動。 下面的代碼編譯得很好:

 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.確實沒有std::unique_ptr<T>的復制構造器,function 不應該接受聲明為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;
} 

不編譯?

有人可以闡明這件事嗎?

1.確實沒有std::unique_ptr<T>的復制構造器,function 不應該接受聲明為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會調用復制構造函數,你需要再次使用std::moveptr轉換為右值

std::unique_ptr<T> f(std::unique_ptr<T> && ptr) { 
    return std::move(ptr); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM