Search code examples
c++c++11returndefault-valuedefault-constructor

How to elegantly return an object that is default-initialized?


I have a class like below:

class VeryVeryVeryLongTypeName
{
    bool is_ok;

    VeryVeryVeryLongTypeName() : is_ok(false) {}
};

VeryVeryVeryLongTypeName f()
{
    VeryVeryVeryLongTypeName v;

    ... // Doing something

    if (condition_1 is true)
    {
        return v;
    }
    else
    {
        return VeryVeryVeryLongTypeName();
    }

    ... // Doing something

    if (condition_2 is true)
    {
        return v;
    }
    else
    {
        return VeryVeryVeryLongTypeName();
    }    
}

I think the statement return VeryVeryVeryLongTypeName(); is very tedious and ugly, so, my question is:

How to elegantly return an object that is default-initialized?

or in other words:

Is it a good idea to add a feature into the C++ standard to make the following statement is legal?

return default; // instead of return VeryVeryVeryLongTypeName();

Solution

  • This is very much more succinct:

       return {};