Pergunta

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.

Foi útil?

Solução

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));
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top