destructor - Issues with desctructor called twice in C++ class having 'has-a' relationship -
i have class a, contains object of class b. private object. when tried access b's member variable using a's object, somehow b's desctructor getting called. not able understand why b's destructor getting called here?
output of following code is:
in b ctor in ctor 10 in b dtor <------ why ? in dtor in b dtor
code sample:
#include "stdafx.h" #include <iostream> using namespace std; //implementaion of b class class b { public: int bval1; b::b(void) { cout << "in b ctor" << endl; bval1 = 10; } b::~b(void) { cout << "in b dtor" << endl; } }; //implementaion of class having private b's object ( composition ) class { private: b b; public: a::a(void) { cout << "in ctor" << endl; } a::~a(void) { cout << "in dtor" << endl; } b a::func2(void) { return b; } }; int _tmain(int argc, _tchar* argv[]) { a; //ctor calling order : b followed cout << a.func2().bval1 << endl; //why additional b's destructor getting called here ??? return 0; //dtor calling order : followed b }
my apologies long code.
you function
b a::func2(void) { return b; }
returns copy of object of type b
. have temporary local version in main()
function. a::b
object , temporary b
object both destroyed, therefore have 2 calls b::~b()
.
your main() function equivalent this:
int _tmain(int argc, _tchar* argv[]) { a; //ctor calling order : b followed b b = a.func2(); cout << b.bval1 << endl; //why additional b's destructor getting called here ??? return 0; //dtor calling order : b, followed a::b followed followed }
try writing this:
const b& a::func2(void) { return b; }
this give 1 call of b::~b()
.
Comments
Post a Comment