Use of C ++ 11 smart pointer unique_ptr -- Take sorting binary tree as an Example
You can use smart pointers to simplify memory management. Take the tree as an example. If a common pointer is used, it is usually used to insert a new node and call delete in the destructor. However, with the unique_ptr smart pointer, delete is not required in the destructor, because when the unique_ptr pointer P ends (for example, for local variables, the program runs out of the scope of local variables ), P will automatically delete its resources (the space pointed by the pointer ). Shared_ptr is more complex. shared_ptr maintains a use count, that is, how many pointers share this resource. When the use count is 0, the resource is automatically released. There is a wiki dedicated to explaining this mode (the acquisition and release of resources and object lifecycle binding), http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization This article focuses on unique_ptr, if not familiar with, you can first read this: http://www.cplusplus.com/reference/memory/unique_ptr/ here with the simple implementation of sorting binary tree to show how to use unique_ptr, we only implement insert an int, and the function of traversing all the numbers in the middle order, this is enough to explain how to use unique_ptr (in fact, I don't quite write the balance of Binary Trees--) TreeNode represents a tree node, including an int value, and a smart pointer pointing to the left and right subtree. We have implemented insert (int) and inOrder () in both TreeNode and BST. The methods in BST basically call the corresponding method of TreeNode (the BST method is just a wrapper, what really works is the corresponding method in TreeNode) copy the Code # include <cstdio> # include <iostream> # include <sstream> # include <string> # include <memory> using namespace std; class TreeNode {public: unique_ptr <TreeNode> left; unique_ptr <TreeNode> right; int val; TreeNode () {} TreeNode (int value): val (value) {} void insert (int value) {if (value <= val) {I F (left) {left-> insert (value);} else {left. reset (new TreeNode (value) ;}} else {if (right) {right-> insert (value) ;}else {right. reset (new TreeNode (value) ;}} void inOrder (stringstream & ss) {if (left) {left-> inOrder (ss );} ss <val <""; if (right) {right-> inOrder (ss) ;}}; class BST {public: BST (); virtual ~ BST (); void insert (int value); string inOrder (); private: unique_ptr <TreeNode> root;}; BST: BST () {} BST ::~ BST () {} void BST: insert (int value) {if (root) {root-> insert (value);} else {root. reset (new TreeNode (value) ;}} string BST: inOrder () {if (root) {stringstream ss; root-> inOrder (ss); return ss. str ();} else {return "" ;}} int main (int argc, const char * argv []) {BST bst; bst. insert (4); bst. insert (5); bst. insert (2); bst. insert (1); cout <bst. inOrder () <endl; return 0 ;}