std::optional as a template parameter for std::atomic

Viewed 723

Is it legal to use next code with initialization:

std::atomic<std::optional<uint64_t>> value{std::nullopt};
const auto loadedValue{value.load()};
assert(false == loadedValue);

I read that template type for std::atomic should be TriviallyCopyable but std::optional is not.

Note: Without initialization with std::nullopt I had undefined behaviour, namely true == loadedValue.

1 Answers

std::optional<T> is required to be as TriviallyCopyable as T itself is. This was added in a defect report post-C++17, but all std::optional implementations ought to implement it.

Related