● 用类型限制用户
class Date { public: Date(int month, int day, int year); ... }; Date d(30, 3, 1995); // 日、月用反了 Date d(2, 30, 1995); // 日、月不匹配
重新设计接口:
struct Day { explicit Day(int d) :val(d) {} int val; }; struct Month { explicit Month(int m) :val(m) {} int val; }; struct Year { explicit Year(int y) :val(y){} int val; }; class Date { public: Date(const Month& m, const Day& d, const Year& y); ... }; Date d(30, 3, 1995); // 1. 用“类型”控制用户 Date d(Day(30), Month(3), Year(1995)); // 1. 对Date的使用 Date d(Month(3), Day(30), Year(1995)); // 1. 只有这样写才行
如果想限制用户对月份的误用,可以用类:
class Month { public: static Month Jan() { return Month(1);} static Month Feb() { return Month(2);} ... static Month Dec() { return Month(12);} ... private: explicit Month(int m); // 严禁用户创建自己的月份 ... }; Date d(Month::Mar(), Day(30), Year(1995)); // 这比写个2或3要麻烦多了,用户不会误写
● 防止客户写出下面代码的方法,是用const限制operator*的返回值
if (a * b = c) ... // 其实想写成 (a * b == c)
● 如果要求客户必须记住,那么他们就有可能忘记
比如申请资源的释放,强制用户使用智能指针管理:
std::tr1::shared_ptr<Investment> createInvestment();
可以为shared_ptr指定一个deleter,该deleter会在引用计数为零时自动调用。
比如有个函数getRidOfInvestment作为deleter传给shared_ptr的某个ctor:
std::tr1::shared_ptr<Investment> createInvestment() { std::tr1::shared_ptr<Investment> retVal(static_cast<Investment*>(0), getRidOfInvestment); retVal = ... ; // make retVal point to the // correct object return retVal; }
当然,如果能直接把正确的指针给shared_ptr的ctor更好。
● shared_ptr来自boost,是原始指针的两倍大;动态分配内存;以virtual形式调用deleter;支持多线程环境下修改引用计数。
本文介绍如何通过C++中的类型系统提高程序的安全性和易用性,包括使用特定类型来约束日期类的构造函数参数,以及利用智能指针管理资源以避免内存泄漏。
873

被折叠的 条评论
为什么被折叠?



