Reputation: 1829
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
Reputation: 303586
The copy constructor is specified as:
optional(const optional<T>& rhs);
3 Requires:is_copy_constructible_v<T>
istrue
.
4 Effects: Ifrhs
contains a value, initializes the contained value as if direct-non-list-initializing an object of typeT
with the expression*rhs
.
5 Postcondition:bool(rhs) == bool(*this)
.
6 Throws: Any exception thrown by the selected constructor ofT
.
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