Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++17

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>>
like image 580
goneskiing Avatar asked Jun 03 '16 19:06

goneskiing


People also ask

What does trivially copyable mean?

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.

Does Optional make a copy?

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.

Is STD array trivially copyable?

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.

What is std :: optional in C++?

(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.


1 Answers

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.

like image 156
Barry Avatar answered Sep 19 '22 23:09

Barry