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>>
A trivially copyable class is a class that: has no non-trivial copy constructors, has no non-trivial move constructors, has no non-trivial copy assignment operators, has no non-trivial move assignment operators, and has a trivial destructor.
See the section about "Optional function parameters". When you call the function and pass an instance of T, an optional will be constructed which will own its own copy of T, therefore it will call T's copy constructor.
std::array however, has a static size set at compile time. It does not have internal pointers and can therefore be copied simply by using memcpy . It therefore is trivial to copy.
(since C++17) The class template std::optional manages an optional contained value, i.e. a value that may or may not be present. A common use case for optional is the return value of a function that may fail.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With