jeudi 12 août 2021

Difference of using aggregate initialization and assigning a compound literal in C++

Suppose I declare a struct A:

struct A {
    int x;
    int y;
};

And then I try two kinds of initialization:

1. Aggregate initialization:

struct A a = {
    .x = 5,
    .y = 2,
};

2. Compound literal & copy:

struct A b = (struct A) {
    .x = 5,
    .y = 2,
};

The second one is allowed in both C and C++, while the first one yields an error in C++. After some reading I figured out that C++ has a problem with 1) because you could leave out some vars and the order of initialization is not guaranteed. But how is this different in the second example?

Aucun commentaire:

Enregistrer un commentaire