程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++11 智能指針unique_ptr使用 -- 以排序二叉樹為例

C++11 智能指針unique_ptr使用 -- 以排序二叉樹為例

編輯:C++入門知識

C++11 智能指針unique_ptr使用 -- 以排序二叉樹為例


用智能指針可以簡化內存管理。以樹為例,如果用普通指針,通常是在插入新節點時用new,在析構函數中調用delete;但有了unique_ptr類型的智能指針,就不需要在析構函數中delete了,因為當unique_ptr類型的指針P生命結束時(比如對於局部變量,程序執行到局部變量的作用域范圍之外),P會自動delete它擁有的資源(指針指向的空間)。對於shared_ptr,情況更加復雜一些,shared_ptr會維護一個use count,即有多少個指針共享這一資源,當use count為0時,資源被自動釋放。       有一篇wiki專門解釋了這種模式(將資源的獲取與釋放與對象的生命周期綁定),http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization       這篇文章主要關注unique_ptr,如果不熟悉,可以先讀一下這個:http://www.cplusplus.com/reference/memory/unique_ptr/       這裡用排序二叉樹的簡單實現來展示如何使用unique_ptr,我們只實現插入一個int,以及中序遍歷輸出所有數字的功能,這已經足以解釋unique_ptr的使用方法(其實是,我不太會寫二叉樹的平衡- -)       TreeNode代表一個樹節點,包括一個int值,和指向左右子樹的智能指針。我們在TreeNode和BST裡都實現了insert(int)和inOrder(),BST中的方法基本上是調用TreeNode的對應方法(BST的方法只是一個wrapper,真正干活的是TreeNode裡的對應方法)   復制代碼 #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) {             if (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; }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved