簡體   English   中英

std :: unique_ptr和有什么不一樣 <type> 並鍵入&amp;&amp;?

[英]What is the difference between std::unique_ptr<type> and type&&?

我無法得到兩個變體之間的區別:

class test {
    std::unique_ptr<std::vector<float>> m_field;
    test(const std::vector<float>&& values) : m_field{std::make_unique<vector<float>>(std::move(values))} {}
};  

class test {
    const std::vector<float>&& m_field;
    test(const std::vector<float>&& values) : m_field{std::move(values)} {}
}; 

在第一個變量中,默認析構函數將自動刪除unique_ptr和內部vector但是在第二個變量中,默認析構函數將如何工作?
哪種變體更好?
PS也許很簡單,但是我正在尋找並且找不到。 我的英語不好,請不要將我發送給嚴格的文檔。

當我們在構造const中刪除const時,第一個test類很有用,它應該是

class test {
public:
std::unique_ptr<std::vector<float>> m_field;
test(std::vector<float>&& values) : m_field{std::make_unique<vector<float>>(std::move(values))} {}
};  

因為可以對非const對象執行移動操作。 例如

vector<float> v(20, 3.0);
test t(move(v));
cout << v.size() << endl; // print 20 if `const` will be in constructor definition
                     // print 0 if `const` specifier is missed in constructor, object was moved  

第二類考試是胡說八道。 此類的析構函數不執行任何操作。 在構造函數中, m_field成員被初始化並指向傳遞的向量,僅此而已,該類的ctor / dtor不再做任何事情。

暫無
暫無

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

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