2

I've read one of your answers (Will an 'empty' constructor or destructor do the same thing as the generated one?). You wrote: "Let's assume the object of type C is created in the definition of A's constructor in the .cpp file, which also contains the definition of struct C. Now, if you use struct A, and require destruction of an A object, the compiler will provide an implicit definition of the destructor, just like in the case above. That destructor will also implicitly call the destructor of the auto_ptr object. And that will delete the pointer it holds, that points to the C object - without knowing the definition of C! That appeared in the .cpp file where struct A's constructor is defined". Could you please explain 2 things for me: 1. why should the destructor of A know C's definition? 2. How does adding A's empty destructor help the sityation? Thank you

Community
  • 1
  • 1
Victoria
  • 21
  • 2

1 Answers1

2

1) The destructor of A should know how to destroy C since A may contain an auto_ptr to C. auto_ptr'd objects are expected to die when the containing object died. Therefore, the destructor of A should know how to destroy a C.

2) The key is that the destructor definition is only written in the .cpp file. This means that calls to the destructor are linked to the object compiled from the .cpp file. When the .cpp file is compiled, it has access to the definition of C (that is what was written in the answer). Therefore, the destructor in the .cpp file can destruct C as needed instead of failing to destruct C as in the case where the destructor was not defined and/or defined at a point where the compiler only saw a forward declararion of class C.

Also, see

The relation between Forward declaration and destructors

Community
  • 1
  • 1
tohava
  • 5,344
  • 1
  • 25
  • 47