I can't get difference between two variants:
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))} {}
};
And
class test {
const std::vector<float>&& m_field;
test(const std::vector<float>&& values) : m_field{std::move(values)} {}
};
In the first variant the default destructor will remove unique_ptr
and inner vector
automatically but what will happen in the second variant how will the default destructor work?
What variant is better?
PS Maybe it's easy but I am looking for and can't find. My English isn't good, please, don't send me to hard docs.
First test
class is useful when we remove const
in constructor, it should be
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))} {}
};
because move operation can be done on non-const object. For example
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
Second test class is nonsense. Destructor of this class does nothing. In constructor m_field
member is initialized and points at passed vector, and it is all, nothing more is done in ctor/dtor of this class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.