C++ Primer 5th Edition Exercises(练习题)13.32

Would the pointerlike version of HasPtr benefit from defining a swap function? If so, what is the benefit? If not, why not?

类指标行为的HasPtr是否也会从定义了swap函式而得到方便?若是,有什么便利之处;若否,又是为什么?

恐怕就是拷贝指定运算子定义时,对参考计数操作上,若仍须在撰写程式码时还要加上如同前面那样自行写定参考计数的计算,那就没有方便太多了。
测试结果却是OK的,和类值的是一样便利!参考计数在swap及copy and swap后并无影响:

HasPtr.h

#ifndef HASPTR_H#define HASPTR_H#include<string>//#include<iostream> //因为.cpp档已include了,所以此可省略引用iostreamclass HasPtr//类指标行为的类别{    friend void swap(HasPtr&,HasPtr&);public:    //预设建构器    HasPtr(const std::string& s = std::string()) : ps(new std::string(s)), i(0), user_cnt(new size_t(1)) {  }    //拷贝建构器    HasPtr(const HasPtr& hp) :ps(hp.ps), i(0), user_cnt(hp.user_cnt) {         ++* user_cnt;         std::cout << "拷贝建构器 阿弥陀佛" <<std::endl;    }    //拷贝指定运算子    //HasPtr& operator=(const HasPtr& hp) {    //  ++* hp.user_cnt;    //  //和解构器~HasPtr()做的是同一件事:    //  //if (-- * user_cnt == 0)    //  //{    //  //  delete ps;    //  //  delete user_cnt;    //  //}//以上和解构器~HasPtr()做的是同一件事,只是解构器似乎不能被呼叫,故可另写一个介面或成员函式来用    //  destroy();    //  if (*user_cnt != 0&&ps!=hp.ps) {//不是自拷贝/指定时才执行    //      ps = hp.ps;    //      i = hp.i;    //      user_cnt = hp.user_cnt;    //  }    //  return *this;    //}    HasPtr& operator=(HasPtr);        ~HasPtr() {        //if (-- * user_cnt == 0) {        //  delete ps;        //  delete user_cnt;        //}        destroy();        std::cout << "解构器 阿弥陀佛" << std::endl;    }private:    std::string* ps;    int i;    size_t* user_cnt;    void destroy() {        if (-- * user_cnt == 0) {            delete ps;            delete user_cnt;        }    }};void swap(HasPtr& lhs,HasPtr& rhs) {    using std::swap;    swap(lhs.ps, rhs.ps);    swap(lhs.i, rhs.i);    swap(lhs.user_cnt, rhs.user_cnt);}//copy and swap(拷贝对调)HasPtr& HasPtr::operator=(HasPtr hp) {    swap(*this, hp);    //因为引数hp在传值时已经将参考计数器递增了,故不用以下此行添足    //++* this->user_cnt;//参考计数只要顾到右运算元要递增就好,左运算元递增则交给被置换后的hp区域变数摧毁时呼叫的解构器来判断    return *this;   }#endif // !HASPTR_H

.cpp

#include<iostream>//因为这里include,所以HasPtr.h才可以不用再次include它;如果这行省略,HasPtr.h编译上就会出现错误#include"HasPtr.h"using namespace std;int main() {    HasPtr hp("孙守真"), hp1("南无阿弥陀佛"), hp2("净空老法师"), hp3("海贤老和尚"),hp4("常律老和尚"),hp5("白云老禅师"),hp6;    hp6 = hp;    hp = hp1;}

https://github.com/oscarsun72/prog1-C-Primer-5th-Edition-s-Exercises/tree/exercise13_32_HasPtr_pointerlike_swap/prog1
脸书直播


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章