Can constructing an empty std::optional<T> call T's default constructor?

Is the object stored inside an instance of std::optional<T> guaranteed to be initialised in-place with placement new? This is what I would expect from most implementations, however, I can also imagine the following implementation:

/* pseudocode */
template<typename T> class optional {
    T object;
    bool has_value;
};

In this case, when constructing an std::optional<T> that does not contain a value, T's default constructor would have to be called.
Is it guaranteed that this is not the case, and even if T does have a default constructor, it will not be called?

All I could find on cppreference related to memory management was the following: "If an optional contains a value, the value is guaranteed to be allocated as part of the optional object footprint, i.e. no dynamic memory allocation ever takes place." (https://en.cppreference.com/w/cpp/utility/optional)
However, my "implementation" above also meets this requirement.

Upvotes: 4

Views: 1345

Answers (1)

Miles Budnek
Miles Budnek

Reputation: 30704

The standard requires that a std::optional<T> initialized either by its default constructor or its std::nullopt_t constructor does not initialize its contained T object.

From [optional.ctor] (emphasis mine):

constexpr optional() noexcept;
constexpr optional(nullopt_t) noexcept;
    Postconditions: *this does not contain a value.
    Remarks: No contained value is initialized. For every object type T these constructors are constexpr constructors ([dcl.constexpr]).

Upvotes: 2

Related Questions