Effective C++ 条款18

让接口easy被正确使用,不easy被误用

如题目,我们自己的程序接口是面向用户的,程序的目的不可是解决这个问题,并且要让用户easy使用。所以。必须保证我们的程序接口具有非常强的鲁棒性。

怎么保证接口的鲁棒性,不同情况有不同的处理结果,作者列出了以下几个样例所相应的方法。

1.设计一个class来表示日期

class Date{
public:
 void Date(int month, int day, int year);
 ……
};

以上的构造接口非常easy被用户用错

Date d(30, 3, 1995);//把月和日弄反了

作者的方法是定义新形式。新类型。

struct Day{
explict 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:
 void Date(const Month& m, const Day& d, const Year& y);
 ……
};

2.另外一种情况。为了防止出现以下的赋值把operator*返回const类型。以下的语句就无法通过编译

 if(a*b=c)//这里事实上打算做比較,而不是赋值

3.使用智能指针

shared_prt<Investment> createInvestment()
 {
    shared_prt<Investment> retVal(static_cast<Investment*>(0),
                                    getRidOfInvestment);
    retVal=……;//令retVal指向正确对象
    return retVal;
 }
原文地址:https://www.cnblogs.com/bhlsheji/p/5272561.html