When I need to have a data member which is a type of std::unique_ptr, then I have 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 the code review, one reviewer mentioned that it is a bad habit and he asked me not to use reset if possible. Instead, he suggested to use the following methods:
std::make_unique
or a template function like the following:
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 some special reasons to avoid using std::unique_ptr::reset in the above case?
new
and the call toreset()
. At this point, what was merely a 'bad smell' becomes a problem. – Richard Hodgesreset
. You're changing the state of an already existing object. It makes little sense not to initialize an object that is useless uninitialized. – juanchopanzamake_unique<>
– Richard Hodgesmake_unique
– TheCppZoo