Domanda

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();
È stato utile?

Soluzione

This is very much more succinct:

   return {};

Altri suggerimenti

You can use this class whose instance will implicitly convert into an instance of desired type automatically. This should work even if the default constructor is marked explicit or if you're still using C++03. For C++11, the accepted answer is succinct and better.

const struct default_t
{
     template<typename T>
     operator T() const {   return T{}; }
}default_{};

And use it as:

VeryVeryVeryLongTypeName f()
{
     //...
     return default_;
}

WithExplicitConstructor_VeryVeryVeryLongTypeName g()
{
     //...
     return default_;
}

Online Demo.

You can use this solution everywhere, even in templates:

template<typename T>
typename father::template daughter<T>::grand_son_type h()
{
     //...
     return default_;
}

Hope that helps.

How about typedef ?

class VeryVeryVeryLongTypeName;
typedef class VeryVeryVeryLongTypeName S;

And then use S.

See HERE

As others have pointed out, you can rely on defining a type alias. In C++11 you can use the notation

using SnappyName = VeryVeryVeryLongTypeName;

and then use SnappyName anywhere you want to.

Remember that you will need to come back to your code, say, six months from now. Use an approach which will help you (or your collaborators) understand unequivocally what you meant. Remember: code is written once and read many times. Code for later readability, not for present keystroke savings.

You receive solution to your problem but there is something you should be aware of. The way you write the function prevent copy elusion like NVRO.

The standard authorises compilers to skip useless copy from temporary but it exists some guidelines to match the condition to enable the optimisation.

In the function body, you must either return the same named objet and nothing else, or always return an object construction. Mixing the two and you loose the very valuable optimization.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top