建立新类型
1、客户忘记区分年月日了,很显然这是不符合逻辑的,需要一个封装类型来区分年 月 日
class Date {public:Date(int year,int month,int day);};Date d(29,12,3);
2、添加年月日的封装类型
struct Year {explicit Year(int y) : year(y) {}int year;};struct Month {explicit Month(int m) : month(m) {}int month;};struct Day {explicit Day(int d) : day(d) {}int day;};Date d(Year(2022),Month(12),Day(12));
束缚对象值
一年只有12月份,需要对于月份加以限制
class Month {public:static Month Jan() { return Month(1) };static Month Feb() { return Month(2) };……private://阻止生成除了12月份之外新的月份explicit Month(int m);};Date d(Year(2022),Month::Jan(),Day(12));
为什么要用static函数?考虑到non-local static变量的初始化顺序,将non-local static变量转换为local static变量
与内置类型的行为兼容
比如之前对于operator=返回值设置为const,可以避免 if(a * b = c) 这种错误
可以以int为范本
接口的一致性
消除客户的资源管理责任
1、
Investment* createInvestment();
返回一个Investment类型的指针,但是容易造成错误:指针没有被删除 或者 同一个指针被删除两次
秉承着资源和对象绑定的想法,可以把返回值存储在智能指针里,但是如果客户忘记使用智能指针呢?
2、可以让这个工厂接口直接返回一个智能指针,先发制人
shared_ptr<Investment> createInvestment();
删除器
1、想把工厂函数返回的指针传递给一个函数getRidOfInvestment,而不是直接delete掉
shared_ptr<Investment> createInvestment(0,getRidOfInvestment);
无法通过编译,0需要转型,shared_ptr第一个参数要求的是一个严格的指针
shared_ptr<Investment> createInvestment(static_cast<Investment *>(0),getRidOfInvestment);
shared_ptr<Investment> createInvestment() {shared_ptr<Investment> retVal(static_cast<Investment*>(0),getRidOfInvestment);retVal = xxx;return retVal;}
可以把retVal管理的原始指针在建立retVal之前先确定下来,因为这样比 先将retVal初始化,再做一次赋值操作要好
2、DLL问题
1)跨DDL问题:对象在一个DDL被new,却在另一个DDL被delete
2)但是shared_ptr不存在这个问题,删除器所在的DDL和诞生的DDL是同一个
shared_ptr<Investment> createInvestment() {return shared_ptr<Investment>(new Stock);}
可以把返回的shared_ptr传递给其他DDL,无需在意DDL问题。因为指向Stock的shared_ptr会追踪记录 - 当引用计数变为0时调用的DDL的delete
3)可以自动解除互斥锁
