In the class initialization and initialization list

I recently discovered that you cannot have in the initialization list and class initialization at the same time. The following code failed to execute:

struct s
{
    int i=0;    
};
int main() {
    s s1; //s1.i = 0
    //s s2={42}; //fails
    return 0;
}

If I remove the initialization in the class, the list of initializers works fine!

Can someone explain to me why such a thing is not allowed?

+4
source share
2 answers

This is actually allowed in C ++ 14.

struct s
{
    int i=0;    
};

int main() {
    s s1;
    s s2 = {42}; // succeeds
}

Your compiler probably just doesn't implement the new rule in C ++ 14. However, the latest version of clang accepts this and does the right thing in C ++ 14 mode.

​​ ++ 11, , . , PoD, . , . , , , ++ 14 .

+7

:

s s1 = { 42 };

, s , , int std::initializer_list.

, s , .

, :

struct s
{
    s(int i) : i(i) {}
    int i=0;    
};

, ++ 14.

. ....

+4

All Articles