建立新类型

1、客户忘记区分年月日了,很显然这是不符合逻辑的,需要一个封装类型来区分年 月 日

  1. class Date {
  2. public:
  3. Date(int year,int month,int day);
  4. };
  5. Date d(29,12,3);

2、添加年月日的封装类型

  1. struct Year {
  2. explicit Year(int y) : year(y) {}
  3. int year;
  4. };
  5. struct Month {
  6. explicit Month(int m) : month(m) {}
  7. int month;
  8. };
  9. struct Day {
  10. explicit Day(int d) : day(d) {}
  11. int day;
  12. };
  13. Date d(Year(2022),Month(12),Day(12));

束缚对象值

一年只有12月份,需要对于月份加以限制

  1. class Month {
  2. public:
  3. static Month Jan() { return Month(1) };
  4. static Month Feb() { return Month(2) };
  5. ……
  6. private:
  7. //阻止生成除了12月份之外新的月份
  8. explicit Month(int m);
  9. };
  10. Date d(Year(2022),Month::Jan(),Day(12));

为什么要用static函数?考虑到non-local static变量的初始化顺序,将non-local static变量转换为local static变量

与内置类型的行为兼容

比如之前对于operator=返回值设置为const,可以避免 if(a * b = c) 这种错误
可以以int为范本

接口的一致性

比如STL容器的接口就很一致,都有size接口等等

消除客户的资源管理责任

1、

  1. Investment* createInvestment();

返回一个Investment类型的指针,但是容易造成错误:指针没有被删除 或者 同一个指针被删除两次
秉承着资源和对象绑定的想法,可以把返回值存储在智能指针里,但是如果客户忘记使用智能指针呢?
2、可以让这个工厂接口直接返回一个智能指针,先发制人

  1. shared_ptr<Investment> createInvestment();

3、删除器

删除器

1、想把工厂函数返回的指针传递给一个函数getRidOfInvestment,而不是直接delete掉

  1. shared_ptr<Investment> createInvestment(0,getRidOfInvestment);

无法通过编译,0需要转型,shared_ptr第一个参数要求的是一个严格的指针

  1. shared_ptr<Investment> createInvestment(static_cast<Investment *>(0),getRidOfInvestment);
  1. shared_ptr<Investment> createInvestment() {
  2. shared_ptr<Investment> retVal(static_cast<Investment*>(0),getRidOfInvestment);
  3. retVal = xxx;
  4. return retVal;
  5. }

可以把retVal管理的原始指针在建立retVal之前先确定下来,因为这样比 先将retVal初始化,再做一次赋值操作要好

2、DLL问题

1)跨DDL问题:对象在一个DDL被new,却在另一个DDL被delete
2)但是shared_ptr不存在这个问题,删除器所在的DDL和诞生的DDL是同一个

  1. shared_ptr<Investment> createInvestment() {
  2. return shared_ptr<Investment>(new Stock);
  3. }

可以把返回的shared_ptr传递给其他DDL,无需在意DDL问题。因为指向Stock的shared_ptr会追踪记录 - 当引用计数变为0时调用的DDL的delete
3)可以自动解除互斥锁