std::unique_ptr<type> 和 type&& 有什么区别?

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

本文关键字:type 什么 区别 gt unique lt std ptr      更新时间:2023-10-16

我无法在两个变体之间获得区别:

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,但是在第二个变体中会发生什么默认破坏者将如何工作?

什么变体更好?
P.S。也许很容易,但我在寻找并且找不到。我的英语不好,请不要把我寄给硬文档。

当我们在构造函数中删除 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中无需完成。