Is it a bad habit to initialize unique_ptr with reset?

When I need to have a data element that is of type std :: unique_ptr, then I usually used std :: unique :: reset to initialize this unique_ptr with a new object.

The following is a simplified example:

class A {
 public:
  void SetValue(int x) {
    data_.reset(new B(x));
  }

 private:
  std::unique_ptr<B> data_;
};

In a code review, one reviewer mentioned that this is a bad habit, and he asked me not to use reset, if possible. Instead, he suggested using the following methods:

std::make_unique

or a template function such as:

template <typename T>
struct MakeUniqueResult {
  using scalar = std::unique_ptr<T>;
};
template <typename T, typename... Args>
typename internal::MakeUniqueResult<T>::scalar
MakeUnique(Args&&... args) {  
  return std::unique_ptr<T>(
      new T(std::forward<Args>(args)...));  
}

Are there any special reasons to avoid using std :: unique_ptr :: reset in the above case?

+4
source share
1 answer

, std::make_unique std::unique_ptr::reset .

std::make_unique .

, , :

Frobnicate(std::unique_ptr<Foo>(new Foo), std::unique_ptr<Bar>(new Bar(3)));

, , . , , , .

std::make_unique:

Frobnicate(std::make_unique<Foo>(), std::make_unique<Bar>(3));

unique_ptrs , , , .

, std::make_unique .

+5

Source: https://habr.com/ru/post/1619408/


All Articles