goneskiing
goneskiing

Reputation: 1829

Will std::optional be a trivially copyable type if the contained type is a trivially copyable type

If the type T in a std::optional is a trivially copyable type will the std::optional be trivially copyable. I ask as I would like to use it in an atomic, so is the following valid for some trivially copyable type T

std::atomic<std::optional<T>>

Upvotes: 18

Views: 2550

Answers (1)

Barry
Barry

Reputation: 303586

The copy constructor is specified as:

optional(const optional<T>& rhs);
3 Requires: is_copy_constructible_v<T> is true.
4 Effects: If rhs contains a value, initializes the contained value as if direct-non-list-initializing an object of type T with the expression *rhs.
5 Postcondition: bool(rhs) == bool(*this).
6 Throws: Any exception thrown by the selected constructor of T.

Nothing here requires that the optional be trivially copyable, but by the as-if rule, nothing here prevents an implementation from choosing to do so. In the libstdc++ implementation for instance, optional<T> is not trivially copyable for any T.

The only explicit discussion of triviality is that if T is trivially destructible, then optional<T> shall also be trivially destructible.

Upvotes: 14

Related Questions