Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to declare a large variable depending on a condition

Tags:

c++

Am reading through (the) C++ Core guidelines and encountered this rule: "Don’t declare a variable until you have a value to initialize it with" https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es22-dont-declare-a-variable-until-you-have-a-value-to-initialize-it-with

It describes the following code as bad:

SomeLargeType var;

if (cond)   // some non-trivial condition
    Set(&var);
else if (cond2 || !cond3) {
    var = Set2(3.14);
}
else {
    var = 0;
    for (auto& e : something)
        var += e;
}

Unfortunately this point fails to describe a way to how to solve this exact issue. Sometimes you just have to initialize a large object differently depending on a condition. The only circumvent that comes to my mind is something like:

SomeLargeType * var;

if (cond)   // some non-trivial condition
    var = new SomeLargeType(123);
else if (cond2 || !cond3) {
    var = new SomeLargeType(3.14);
}

However even if I use a smartpointer, this feels somehow unnecessary/unsafe and most of all, worse than the initial way.

What is the optimal solution?

like image 369
AlexGeorg Avatar asked Nov 04 '19 11:11

AlexGeorg


1 Answers

You can use a function. Also, don't use bare pointers with ownership (I assume that there's a guideline for this too). Example:

std::unique_ptr<SomeLargeType>
make_something(bool cond, bool cond23)
{
    if (cond)
        return std::make_unique<SomeLargeType>(123);
    else if (cond23)
        return std::make_unique<SomeLargeType>(3.14);
    else
        return nullptr;
}

// usage
std::unique_ptr<SomeLargeType> var = make_something(cond, cond2 || !cond3);

If there's no way for this function to be reusable, then a lambda might be appropriate, as shown by Sopel

like image 127
eerorika Avatar answered Nov 14 '22 23:11

eerorika