日曜日, 8月 17, 2014

auto_ptrからunique_ptrへ移行

auto_ptrは既にdeprecatedとされており,短所もご存じの通りかと思う.(こちらはその短所を簡潔に良くまとめている)
auto_ptrからunique_ptrへの移行は非常に簡単である.

以下の例はauto_ptrの代わりにunique_ptrを使用して簡単なツリーをインオーダ順で走査するコード.

tree.h

#ifndef __TREEPRJ_TREE_H__
#define __TREEPRJ_TREE_H__

#include <string>
#include <memory>
#include <iostream>


class Node {
public:
 Node(int idVal, std::string nameVal) :id(idVal), name(nameVal){}
 virtual ~Node() { std::cout << "ID[" << id << "] is being released" << std::endl; }
 int id;
 std::string name;
 std::unique_ptr<Node> l;
 std::unique_ptr<Node> r;
};


class Tree {
private:
 std::unique_ptr<Node> root;
 void _add(std::unique_ptr<Node>& n, int id, std::string name);
 void _traverseInorder(std::unique_ptr<Node>& n);
public:
 Tree(int id, const std::string n);
 virtual ~Tree() {}
 void add(int id, std::string name);
 void traverseInorder();

};

#endif


tree.cpp
#include "tree.h"
#include <iostream>

Tree::Tree(int id, const std::string name) {

 root.reset(new Node(id, name));

}

void Tree::add(int id, std::string name) {

 _add(root, id, name);

}

void Tree::_add(std::unique_ptr<Node>& n, int newId, std::string newName) {

 if ( !n ) return;

 if (n->id > newId) {
  if (n->l) {
   _add(n->l, newId, newName);
  }
  else {
   n->l.reset(new Node(newId, newName));
  }
 }
 else {
  if (n->r) {
   _add(n->r, newId, newName);
  }
  else {
   n->r.reset(new Node(newId, newName));
  }
 }

}

void Tree::traverseInorder() {

 _traverseInorder(root);

}

void Tree::_traverseInorder(std::unique_ptr<Node>& n) {

 if (!n) return;
 _traverseInorder(n->l);
 std::cout << "ID:" << n->id << ",NAME:" << n->name << std::endl;
 _traverseInorder(n->r);

}

int main() {

 Tree t(30, "The Colton");
 t.add(25, "The Warwick");
 t.add(21, "Hawthorne Court");
 t.add(45, "Hampton Court Garden");
 t.add(15, "The Belvedere");
 t.add(50, "Stratford Hall");
 t.traverseInorder();

}


0 件のコメント: