Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional invocation of constructor [closed]

Tags:

c++

Suppose some class foo has two custom constructors, say foo::foo(bar const &) and foo::foo(baz const &). What would be considered good style for invoking either one depending on some condition. For example:

bar a;
baz b;
foo my_foo;
if (...) {
    my_foo = foo(a);
} else {
    my_foo = foo(b);
}

would require foo to be default constructible (which is not very sensible in the concrete case I have in mind) and is essentially wasting time (and memory) on the creation (and deletion) of the default-constructed temporary object. Because of scope, one cannot declare my_foo inside the if or else blocks.

An alternative would be to use a pointer and construct with new. This would be less efficient (indirection, heap allocation) and potentially unsafe (no guarantee pointer isn't dangling; need to delete, though the latter may be taken care of by using std::unique_ptr).

I found one way to do it:

foo my_foo = (...) ? foo(a) : foo(b);

which works because the ternary operator is guaranteed to be exhaustive and thus scope is not an issue.

I'm not a big fan of the ternary operator and might want to do some other things in the conditional blocks before invoking the ctors. Is there an elegant way to achieve the same thing with the traditional if-else syntax?

like image 989
Jonas Greitemann Avatar asked Jan 30 '23 13:01

Jonas Greitemann


1 Answers

You could use a lambda

const foo my_foo = [&] 
    {
          if (...) 
               return foo(a);
          else 
               return foo(b);
    } ();
like image 115
Robert Andrzejuk Avatar answered Feb 08 '23 16:02

Robert Andrzejuk