mardi 3 septembre 2019

An invalid default member initializer that is never used

Please consider the following code:

template <typename T>
struct Test
{
    Test() = default;

    explicit Test(const T& arg)
     : m_member(arg)
    {
    }

    T     m_member{};
};

int main()
{
    Test<int>       t1;

    int             v2 = 34;
    Test<int&>      t2(v2);     // (!)

    return 0;
}

Should the code above compile and exhibit no undefined behavior?

The line marked (!) instantiates the class template Test with a parameter of reference type. In this case, the default initializer for member Test::m_member is invalid (well, a reference must be initialized with some object). But on the other hand, the default constructor (the only one which could have used that default initializer) is never used in the program, and so it shouldn't be instantiated.

Under C++11, is the compiler allowed/required to attempt/skip the instantiation of a default initializer for a member which is not used in the instantiated constructors (i.e. the program doesn't instantiate any of the constructors which could require that initializer)?

Aucun commentaire:

Enregistrer un commentaire