2

In C++17, does it make any difference to declare the default constructor as default in an aggregate, as in:

struct A {
   A() = default;
   int v;
};

vs relying on it being implicitly defined, as in:

struct A {
   int v;
};

I understand that in C++20, declaring the constructor causes A to not be an aggregate. As I am switching our build flag to C++20, I'd like to just remove the constructor declaration so the structs remain aggregates, but I'm wondering is this has any side effect?

greg_p
  • 315
  • 1
  • 8

1 Answers1

0

does it make any difference to declare the default constructor as default in an aggregate

No differences in this case. Regardless whether you explicitly writes a default constructor =default, the compiler generates the same thing, and your variable v is initialized to 0 anyway.

artm
  • 17,291
  • 6
  • 38
  • 54
  • 2
    `v` will not be initialized to zero by the defaulted default constructor. – NathanOliver Apr 21 '23 at 20:44
  • ok so it's "default" value is initialized when we define it eg `struct A a1;' ? – artm Apr 21 '23 at 20:59
  • @artm There is no "_"default" value_". The constructor doesn't change the value of the `int` member at all (whether implicitly-defined or explicitly defaulted) and leaves it with an indeterminate value (or zero value if the object was zero-initialized beforehand). – user17732522 Apr 21 '23 at 21:03
  • For built in types like `int`, default initialization is no initialization, the `int` just has some garbage value. `A foo;` leaves `v` with an indeterminate value. `A foo{}` (or if you could write `A foo()`) value initializes `foo` and that will zero initialize `v`. – NathanOliver Apr 21 '23 at 21:04
  • @NathanOliver so you mean in this case `v` is never initialised to zero - regardless of whether the default ctor is there or not? there is this related answer talking about "value-initialised" - not sure if it's exactly the same here: https://stackoverflow.com/a/3803288 – artm Apr 21 '23 at 22:15
  • If you do `A foo;` then yes, `v` will not be initialized as you are doing default initialization. – NathanOliver Apr 21 '23 at 22:22
  • @NathanOliver and `A foo();` then `v` will be initialized - correct ? – artm Apr 21 '23 at 22:23
  • 1
    Yes, except that you can't do `A foo()` as that declares a function. You have to do `A foo{};` or `A foo = A();` – NathanOliver Apr 21 '23 at 22:29