In Bjarne Stroustrup's "The C++ Programming Language (4th edition)" in section 17.6 (Generating Default Operations) it mentions this:
If the programmer declares a copy operation, a move operation, or a destructor for a class, no copy operation, move operation, or destructor is generated for that class.
Thus, I'm confused why the SubObj
destructor is called in this program:
#include <iostream>
using namespace std;
class SubObj {
public:
~SubObj() {
cout << "SubObj Destructor called" << endl;
}
};
class Obj {
private:
SubObj so;
public:
Obj() {};
Obj(const Obj& o) {};
};
int main() {
Obj();
cout << "Program end" << endl;
}
When compiling with g++ I get the following output:
$ ./a.out
SubObj Destructor called
Program end
Based on my understanding, I expected the default destructor for Obj
to not be auto-generated because I defined a copy operation for Obj
. And thus, I expected that the SubObj
member of Obj
would not be destroyed because there is no destructor for Obj
.
Thus, I'm wondering: are object members automatically destroyed even without a destructor? Or is a destructor somehow being auto-generated for this example?
Edit:
Later in the book (17.6.3.4), when referring to an example, Bjarne mentions:
We defined copy assignment, so we must also define the destructor. That destructor can be
=default
because all it needs to do is to ensure that the memberpos
is destyored, which is what would have been done anyway had the copy assignment not been defined.
Based on the answers so far, it sounds appears as though Bjarne may have just been wrong on this one.