Quick Q: Why two null constructors for std::unique_ptr?

Quick A: The nullptr_t constructor was added later.

Recently on SO:

Why two null constructors for std::unique_ptr?

For (1), consider that it ensures that both the no-arg constructor unique_ptr() and null-pointer constructor unique_ptr(nullptr_t) have the same compile-time guarantees, i.e. both are constexpr. We can see the difference in §20.8.1.2:

constexpr unique_ptr() noexcept;
explicit unique_ptr(pointer p) noexcept;
...
constexpr unique_ptr(nullptr_t) noexcept
: unique_ptr() { }

Why the two were not combined into a single constructor with a default value is likely historical contingency.

With regards to (2), why we should care about constexpr despite having a non-trivial destructor, consider the answer given here:

constexpr constructors can be used for constant initialization, which, as a form of static initialization, is guaranteed to happen before any dynamic initialization takes place.

For example, given a global std::mutex:

std::mutex mutex;

In a conforming implementation (read: not MSVC), constructors of other objects can safely lock and unlock mutex, becuase std::mutex's constructor is constexpr.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.