I want to store a non-trivial type that is immovable and not copyable in an std::optional
. However the object is constructed by a free function. (example)
struct Foo {
Foo();
Foo(Foo const&) = delete;
Foo(Foo&&) = delete;
Foo& operator=(Foo const&) = delete; // added for completeness
Foo& operator=(Foo&&) = delete; // added for completeness
~Foo();
};
Foo foo();
Without changing Foo
or foo()
;
Thanks to copy elision, I can already do this:
Foo f1 = foo();
And this also compiles, because std::optional
only requires the stored type to be destructible:
std::optional<Foo> f2;
f2.emplace();
But I cannot fill f2
with a function result:
f2 = foo(); // no
f2.emplace(foo()); // no
Obviously, because this would require copies or moves of Foo
. This is likely impossible, but have I overlooked something?