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?
source
share