I do not want to copy a container while sending it to the constructor, then I use reference to a local variable. Something in this code makes me nervous.
The code is correct as a copy of tmp_ar
is being made by m_ar(ar)
: mc
has no reference to the local variable tmp_ar
so there is no lifetime dependency between mc
and tmp_ar
. Problems can arise if an object stores a reference to another object and attempts to use that reference when the other object has been destructed (see dangling pointer, same applies to reference).
The tmp_ar
could be std::move()
d instead to avoid the copy if tmp_ar
is no longer required after it has been passed as constructor argument:
class MyClass {
public:
MyClass(std::vector<int> ar) : m_ar(std::move(ar)) {};
private:
std::vector<int> m_ar;
};
std::vector<int> tmp_ar {0, 1, 2};
// Use 'tmp_ar' ...
MyClass mc(std::move(tmp_ar));