13.2. Copy Control and Resource Management

来源:互联网 发布:java 生成汉字验证码 编辑:程序博客网 时间:2024/05/19 09:13
//Exercises Section 13.2//Exercise 13.22: Assume that we want HasPtr to behave like a value.That//is, each object should have its own copy of the string to which the objects//point.We’ll show the definitions of the copy - control members in the next//section.However, you already know everything you need to know to//implement these members.Write the HasPtr copy constructor and copyassignment//operator before reading on.//Exercises Section 13.2.1//Exercise 13.23: Compare the copy - control members that you wrote for the//solutions to the previous section’s exercises to the code presented here.Be//sure you understand the differences, if any, between your code and ours.class HasPtr {public:HasPtr(const std::string &s = std::string()) :ps(new std::string(s)), i(0) { }HasPtr(const HasPtr &hp) : ps(new std::string(*hp.ps)), i(hp.i) { }HasPtr &operator=(HasPtr &hp) {auto newp = new string(*hp.ps);delete ps;ps = newp;i = hp.i;return *this;}~HasPtr() {delete ps;}private:string *ps;int i;};int main() {return 0;}//Exercise 13.24: What would happen if the version of HasPtr in this section//didn¡¯t define a destructor ? What if HasPtr didn¡¯t define the copy//constructor ?//if didn't define a destructor, a memory leak would occur, compiler synthesized destructor doesn't manage dynamic memory.//if didn't define the copy constructor, it would behave like pointer//Exercises Section 13.2.2//Exercise 13.27: Define your own reference - counted version of HasPtr.class HasPtr {public:HasPtr(const string &s, int i) : use(new size_t(1)), ps(new string(s)), i(i) { }HasPtr(const HasPtr &hp) {ps = hp.ps;i = hp.i;++*use;}HasPtr &operator=(HasPtr &hp) {++*hp.use;if (--*use == 0) {delete ps;delete use;}ps = hp.ps;i = hp.i;return *this;}~HasPtr() {if (--*use == 0) {delete ps;delete use;}}private:size_t *use;string *ps;int i;};//Exercise 13.28: Given the following classes, implement a default constructor//and the necessary copy - control members.//(a)class TreeNode {public:TreeNode() : value(string()), count(new int(1)), left(nullptr), right(nullptr) { }TreeNode(const TreeNode &t) : value(t.value), count(t.count), left(t.left), right(t.right) { }TreeNode &operator=(const TreeNode &t) {++*t.count;if (--*t.count == 0) {delete left;delete right;delete count;}value = t.value;count = t.count;left = t.left;right = t.right;count = t.count;return *this;}~TreeNode() {if (--*count == 0) {delete left;delete right;delete count;}}private:string value;int *count;TreeNode *left;TreeNode *right;};//(b)class BinStrTree {public:BinStrTree() : root(new TreeNode()) { }BinStrTree(const BinStrTree &bst) : root(new TreeNode(*bst.root)) { }BinStrTree &operator=(const BinStrTree &bst) {TreeNode *new_root = new TreeNode(*bst.root);delete root;root = new_root;return *this;}~BinStrTree() { delete root; }private:TreeNode *root;};int main() {return 0;}

阅读全文
0 0