1

While sending stl container by reference it's not as safe as may be. Does it make sense to wrap stl container by smart pointer to send as function argument?

template <typename T> void f(const std::unique_ptr<T> up) { ... } std::unique_ptr<std::vector<char>> array; f(std::move(array)); 

UPD: OK, let's narrow the question. I'm making an instance of some class. I should construct it with a container:

class MyClass { public: MyClass(const std::vector<int>& ar) : m_ar(ar) {}; private: std::vector<int> m_ar; }; std::vector<int> tmp_ar; tmp_ar.push_back(0); tmp_ar.push_back(1); tmp_ar.push_back(2); MyClass mc(tmp_ar); 

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.

4
  • 1
    why would sending by reference would not be safe? and sending by pointer would be? Commented Feb 7, 2014 at 8:17
  • I do not know, I'm still thinking .... Commented Feb 7, 2014 at 8:46
  • What made you to ask this question ? Commented Feb 7, 2014 at 9:36
  • @Drax It is quite important to know if it's sometimes necessary to allocate on heap a pointer to a container. Commented Jun 4, 2021 at 6:10

1 Answer 1

2

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)); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.