Behavior Of Destructor

Hi,
I am trying to work with shared_ptr ,and trying to execute a simple binary tree.
However the behavior of the destructor is confusing me .

This is my Code:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class TreeNode{
	
	public:
	shared_ptr<TreeNode> leftChild;
	shared_ptr<TreeNode> rightChild;
	int val;
	
	TreeNode(int mVal):val(mVal){
		cout<<"Constructor created "<< val <<endl;
	}
	~TreeNode(){
		cout<<"Destructor Called "<< val<<endl;
	}
};
int main(){

		shared_ptr<TreeNode> a = make_shared<TreeNode>(5);
		a->leftChild = make_shared<TreeNode>(8);
		a->rightChild = make_shared<TreeNode>(10);

		return 0;
}

output is :
Constructor created 5
Constructor created 8
Constructor created 10
Destructor Called 5
Destructor Called 10
Destructor Called 8

To my understanding it should have been 10,then 8 and then 5,
but my compiler seems not to agree with me

what am I missing ?
Plzz help

Last edited on
cppreference wrote:
For both user-defined or implicitly-defined destructors, after the body of the destructor is executed, the compiler calls the destructors for all non-static non-variant members of the class, in reverse order of declaration, then it calls the destructors of all direct non-virtual base classes in reverse order of construction (which in turn call the destructors of their members and their base classes, etc), and then, if this object is of most-derived class, it calls the destructors of all virtual bases.

http://en.cppreference.com/w/cpp/language/destructor
good answer above

as a side comment, who exactly is the ownership of leftChild, rightChild, or the tree itself shared with? It looks like a misuse of shared pointers in the making.
Thanks Cubbi,I was wondering over mbozzi's answer.
Now I can track my issue.
Topic archived. No new replies allowed.