std::optional<A>
guarantees that no auxiliary memory allocation will take place. This means that the raw buffer for the potential object of type A
is embedded into std::optional<A>
. It is an integral part of std::optional
's memory footprint. This means that the memory size of std::optional<A>
will always be at least sizeof(A)
, regardless of whether that optional A
object currently lives or not. That is how much std::optional<A>
will contribute to the total size of B
.
std::unique_ptr<A>
is a pointer. Its size is about the same as the size of a regular naked pointer. That is how much memory std::unique_ptr<A>
itself occupies inside B
. In order to make it point to a valid A
object you will have to allocate that A
elsewhere, independently. When A
exists, it occupies memory. When A
does not exist it does not occupy memory.
The above is something to take into account when making your decision. std::optional<A>
does not involve dynamic memory allocation/deallocation, but the price you pay for that is potentially "wasted" memory inside your std::optional<A>
. Using std::optional
for massively instantiated and/or large objects might prove to be quite wasteful, especially if the object spends most of its lifetime in empty state.
This means that the purpose of std::optional
is not exactly aimed at optional long-term storage. std::optional
is something to be used locally: e.g. as optional local values, optional parameters of functions, optional return values. Long-term use is also OK, as long as you are not instantiating such objects in massive numbers.
std::unique_ptr<A>
does not waste memory, but the price you pay for that is dynamic memory allocation/deallocation.
Of course, ownership semantics is also quite different. std::optional
is copyable. std::unique_ptr
is movable, but not copyable.
nullptr
meaningful in your program?std::optional
will skip dynamic allocation. This usually lead to better performance and less memory overhead. IfaMember
was dynamically allocated only to be able to be null, my choice would bestd::optional
std::optional
then. But be aware that just like values, polymiphism will not work, eg you cannot hold a subclass ofA
in the optional.