If I have two classes D1 and D2, which are both derived from the Base class, and I want to build a specific one based on, say, a Boolean variable, there are various well-known methods, for example, use factory or use smart pointers.
For instance,
std::unique_ptr<Base> b;
if (flag)
{
b.reset(new D1());
}
else
{
b.reset(new D2());
}
But it uses a bunch to allocate, which is okay, but I can think of times when it would be nice to avoid the impact of memory allocation performance.
I tried:
Base b = flag ? D1() : D2();
Base& b = flag ? D1() : D2();
Base&& b = flag ? D1() : D2();
Base&& b = flag ? std::move(D1()) : std::move(D2());
My intention is that D1 or D2 is selected on the stack, and its lifetime ends when b goes beyond. Intuitively, I feel that there must be a way to do this.
I played with lambda functions and found that this works:
Base&& b = [j]()->Base&&{
switch (j)
{
case 0:
return std::move(D1());
default:
return std::move(D2());
}
}();
, , , .
, , , , , , . std:: move, !
, , , , :
?