C++11 Smart Pointer unique_ptr use--take a sort of binary tree as an example

Source: Internet
Author: User

Use smart pointers to simplify memory management. In the case of a tree, if you use a normal pointer, you usually call delete in the destructor when you insert a new node, but with a smart pointer of type UNIQUE_PTR, you do not need to delete it in the destructor, because when Unique_ When the PTR type pointer p is at the end of life (for example, for a local variable and the program executes outside the scope of the local variable), p automatically deletes the resource it owns (the space the pointer points to). For shared_ptr, the situation is more complicated, shared_ptr will maintain a use count, that is, how many pointers share this resource, and when use count is 0 o'clock, the resource is automatically freed.

One wiki specifically explains this pattern, which binds the acquisition and release of resources to the life cycle of the object, http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization

This article focuses on unique_ptr, if unfamiliar, you can read this first: http://www.cplusplus.com/reference/memory/unique_ptr/

Here we use the simple implementation of the sort binary tree to show how to use unique_ptr, we only implement inserting an int, and the function of traversing the output of all the numbers in the middle sequence, which is enough to explain how the UNIQUE_PTR is used (in fact, I am not very good at writing two-fork tree balance-)

TreeNode represents a tree node, including an int value, and a smart pointer to the left and right subtree. We have implemented both insert (int) and inorder () in TreeNode and BST, and the method in BST is basically the corresponding method of calling TreeNode (the method of BST is only a wrapper, the real work is the corresponding method in TreeNode)

#include <cstdio>#include<iostream>#include<sstream>#include<string>#include<memory>using namespacestd;classtreenode{ Public: Unique_ptr<TreeNode>Left ; Unique_ptr<TreeNode>Right ; intVal; TreeNode () {} TreeNode (intvalue): Val (value) {}voidInsertintvalue) {        if(Value <=val) {            if(left) { left-Insert (value); } Else{Left.reset (NewTreeNode (value)); }        } Else {            if(right) { right-Insert (value); } Else{Right.reset (NewTreeNode (value)); }        }    }    voidInorder (stringstream&SS) {        if(left) { left-inorder (ss); } SS<< Val <<" "; if(right) { right-inorder (ss); }    }};classBST { Public: BST (); Virtual~BST (); voidInsertintvalue); stringinorder ();Private: Unique_ptr<TreeNode>root;}; Bst::bst () {}bst::~BST () {}voidBst::insert (intvalue) {    if(root) {root-Insert (value); } Else{Root.reset (NewTreeNode (value)); }}stringBst::inorder () {if(Root) {StringStream ss; Root-inorder (ss); returnSs.str (); } Else {        return ""; }}intMainintargcConst Char*argv[])    {BST BST; Bst.insert (4); Bst.insert (5); Bst.insert (2); Bst.insert (1); cout<< Bst.inorder () <<Endl; return 0;}

It was mentioned that TreeNode may be designated as noncopyable, see http://stackoverflow.com/questions/6679482/ Smart-pointers-for-modelling-a-general-tree-structure-its-iterators, quite reasonable, this implementation is not complicated, you can refer to http://en.wikibooks.org /wiki/more_c%2b%2b_idioms/non-copyable_mixin

C++11 Smart Pointer unique_ptr use--take a sort of binary tree as an example

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.