Q
Q
Qubc2021-10-29 11:03:58
C++ / C#
Qubc, 2021-10-29 11:03:58

Why does the compiler reinitialize an object?

Why is copy ctor called after object initialization?

//-std=gnu++03 -fno-elide-constructors 
//-std=gnu++11 -fno-elide-constructors 

#include <iostream>

class A {
  int data;
public:
  A (void) { std::cout << this << " A::A (void) \n";  }
  A (A const & ref ) { std::cout << this << " A::A (A const &) \n";  }
  ~A(){ std::cout << this << " ~A::A () \n";}
  class B;
  friend B;
  class B {
    A & a;
  public:
    B(A & objc) : a(objc) { std::cout << this << " A::B::B (A &) \n";	}
    B(B const & ref) : a(ref.a) { std::cout << this << " A::B::B (B const &) \n"; }
    ~B(){ std::cout << this << " ~A::B::B () \n";}
};

int main(void) {
  A a;
  // A::B b1 (a); // ok
  A::B b2 = a; // strange

  std::cout << " end " << std::endl;
  return 0;
}


0xff98d148 A::A (void)
0xff98d14c A::B::B (A &)
0xff98d144 A::B::B (B const &)
0xff98d14c ~A::B::B ()
end
0xff98d144 ~A:: B::B ()
0xff98d148 ~A::A ()

https://godbolt.org/z/GEjP95jnh

Why is the copy constructor called? It is clear that optimization will turn it off. But what is the reason? Why does the compiler not like the constructor (A &) that it then rewrites the object again? Or is it just because?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
1
15432, 2021-10-29
@Qubc

Because of assignment. To assign an object of type B to an object of type A, you need to create an intermediate object of type B with the constructor (A::B::B (A &)). And only then assign (A::B::B (B const &)). And delete the temporary object. That's what the compiler thinks

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question