문제

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.

도움이 되었습니까?

해결책

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));
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top