Very stupid mistakes record & # 183; & # 183; & # 183; & # 183; & # 183; & # 183; & # 183; (C ++ new issues of object creation)

Today, the C ++ class machine, ah, is to write a little about the project to achieve binary search tree and its various methods. ???? result hung up on creating objects look back only to find how mentally ???? record now, I hope never to repeat.

Of a total of two classes, BST tree class represents the whole teeth, the root which has a root, nodes and storage container vector; another TreeNode class that represents the leaf nodes, a single node data is an int.

The following is a constructor big mistake:

1 BST::BST() {
2     L = {22,15,60,3,25,11,50,1,27,25,49,40,53,30,19,11};
3     for (auto it = L.begin(); it != L.end(); it++) {
4         treeVec.push_back(&TreeNode(*it));
5     }
6 }

The fourth line did not actually create objects ?????? breakpoints can be found in each object is created is called immediately after the destructor destroyed. Why, because there is simply not allocate memory ?????

Reference: https://blog.csdn.net/qq_18884827/article/details/52334303     :

c ++ inside the object is created, ClassName object (initialization parameters); allocate space inside the stack Stack, automatic release. 
Or use ClassName object = new ClassNam (); heap at the heap space allocated to the manual release.

Look: https://blog.csdn.net/cscmaker/article/details/7019977 :

From the operating results, we can draw when not in use to create new objects, the memory space object is in the stack, its scope only inside the function, the function will be executed after calling the destructor is complete, remove the object.

Creating and using a new object is created on the heap, the programmer must manually to manage the object's memory space.

 

Therefore, the correct leaf node to create a constructor as follows:

 

Do not forget to delete destructor frees the memory:

 

 

 

 

Guess you like

Origin www.cnblogs.com/mrlonely2018/p/11946674.html