0

What exactly occurs to a member variable with a default value, during a defaulted copy/move construction? As so:

struct A {bool a = true;};

A x;
x.a = false;
A y = x;

I can imagine a few different ways this works, equivalently written as

struct A {bool a;}; //no default

//option 1
A::A(const A& other) noexcept : a(other.a) {}

//option 2
A::A(const A& other) noexcept : a(true) {a = other.a;}

//option 3
A::A(const A& other) noexcept {a = other.a;}

//option 4 (hopefully not)
A::A(const A& other) noexcept : a(true) {}

With the obvious exception that using these would make A not TriviallyCopyable

  • [Dupe1](https://stackoverflow.com/questions/71491967/default-copy-move-constructor-efficiency-different), [Dupe2](https://stackoverflow.com/questions/51406033/default-constructor-in-cpp-shallow-or-deep-copy) – Jason Aug 03 '22 at 09:03

1 Answers1

2

A constructor must and will always initialize all the class data members.

Default initializers will be used in constructors where that data member isn't explicitly initialized. The default copy constructors will initialize each data member with a copy of the corresponding data member from the copied object, so default initializers won't be used.

This leads to a case where default initializers will be used in a copy constructor if it's user provided and it lacks that member initializer (thanks to NathanOliver for pointing this out).

E.g.:

A(whatever param) {}            // default initializer used
A(whatever param) : a{true} {}  // default initializer NOT used
A(const A&) = default;          // default initializer NOT used
A(const A&) : a{other.a} {}     // default initializer NOT used
A(const A&) {}                  // default initializer used
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
bolov
  • 72,283
  • 15
  • 145
  • 224
  • 2
    technically it does for constructors if you provide your own and forget to initialize the member: http://coliru.stacked-crooked.com/a/19983168b3aaede4 – NathanOliver Aug 03 '22 at 01:02
  • @NathanOliver wow, I haven't thought of this case. Interesting. Thinking how to edit the a – bolov Aug 03 '22 at 01:04