1

Working on learning how to use smart pointers and C++ in general... Assume that I have the following class:

template<typename T>
class MyClass {
public:
  MyClass(const T& def_val)
private:
  std::unique_ptr<T> default_val;
};

What is the idiomatic way of implementing the constructor if I would only like to store a pointer to an object of type T with the value given in the default_val class member? My understanding is also that I don't have to define a destructor at all, since the unique_ptr will automatically taking care of cleaning up itself?

1
  • unique_ptr<T> owns a pointer to a dynamically-allocated T ... so you need to dynamically-allocate a T and store it in default_val Commented Jan 15, 2015 at 12:05

2 Answers 2

3

The way you have written your code, MyClass can only store a unique pointer to a copy of the constructor parameter:

MyClass::MyClass(const T& def_val)
: default_val(new T(def_val))
{
}

This means that T must be copy constructible.

My understanding is also that I don't have to define a destructor at all, since the unique_ptr will automatically taking care of cleaning up itself?

Correct. That is 1 of 2 main purposes for unique_ptr, the 2nd being the guarantee that it has only one owner.

Sign up to request clarification or add additional context in comments.

Comments

3

If you're using C++11 you could add also a constructor that accepts an rvalue ref

template<typename T>
class MyClass {
public:
  MyClass(T&& def_val) : default_val(new T(std::move(def_val))) {}
  MyClass::MyClass(const T& def_val) : default_val(new T(def_val)) {}
private:
  std::unique_ptr<T> default_val;
};

now you accept both const ref, generating a copy, or temporaries

2 Comments

You forgot to allocate an object in the T&& constructor.
(Edited to allocate the object in the T&& constructor). N.B. saying "If you're using C++11" is a bit redundant in a question about unique_ptr, which is also tagged c++11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.