std::unique_ptr<type> 和 type&& 有什么区别?
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
,但是在第二个变体中会发生什么默认破坏者将如何工作?
什么变体更好?
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中无需完成。
相关文章:
- "type* = nullptr"的含义是什么
- 有些时候,阶级必须"default copy c'tor" ?当我做"new Type[..]"时会发生什么?
- 警告的原因是什么:"when type is in parentheses, array cannot have dynamic size"?
- 什么原因导致我的"‘FatalError’ in namespace ‘Foam’ does not name a type"错误?
- C++ - "Incomplete type not allowed"错误是什么意思,我该如何修复它?
- const TYPE&- 我什么时候想通过引用 const 来使用?
- 这是什么意思:"member reference type 'Human *' is a pointer; did you mean to use '->'?"
- C++ 中数组的"expression must have pointer-to-object type"是什么?
- 成为"variant type"意味着什么?
- "conversion from void to non scalar type string"是什么意思?
- 无法运行简单的 std::async 和 std::future 测试程序。错误:"has initializer but incomplete type."发生了什么?
- std::unique_ptr<type> 和 type&& 有什么区别?
- 在 LLVM 中,调用中函数的位播"type"是什么?如何访问此功能?
- C++中的"vector<type[n]>"是什么?
- 当您声明"pointer type"形式(函数)参数"like an const array"时,什么是常量?
- 在标准中,什么是"derived-declarator-type"?
- "type-safety"在C++中的确切含义是什么?
- 在OpenCV中,std::vector而不是cv::Mat的"type"是什么解释,我该如何更改它?(C++)
- c++ 声明中的 ::type 是什么意思
- C++ <Type> 和<类型*有什么区别>