Let's say we have a variable
std::optional<T> x;
of type std::optional<T>
for some type T
.
If I want to call a constructor of T
inside x
and initialize it, I can call the member function std::optional::emplace
. As I know, this member function checks if the instance already exists (that is, bool(x)
evaluates to true
), and if that's the case, it first destroys the previously constructed instance and then re-initialize it using the constructor and arguments provided.
I'm wondering if it is possible to do only initialization w/o this checking and destruction. When dealing with std::optional
, it seems quite common to first check if the instance exists and then do some separate works depending on the result. Therefore, it seems reasonable to argue that quite often when we need to emplace an instance inside std::optional
, we already know that it does not contain any initialized instance. Hence, it seems reasonable to provide an "unsafe-version" of std::optional::emplace
that does not check and destroy the previous instance, but std::optional
does not have such a member function. Is there any way to accomplish this?
Perhaps, if there are some guarantees about memory layout for std::optional
(which I guess not), then I can call placement new
operator directly...