您的位置:首页 > 编程语言 > C语言/C++

Effective C++ Item 18 让接口容易被正确使用,不易被误用

2014-05-26 15:18 387 查看
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie

经验1:好的接口很容易被正确使用,不容易被误用。你应该在你的所有接口中努力达成这些性质。

经验2:“促进正确使用”的办法包括接口的一致性,以及与内置类型的行为兼容

经验3:“阻止误用”的办法包括建立新类型、限制类型上的操作,束缚对象值,以及消除客户的资源管理责任。

示例1:建立新类型

struct Day{
explicit Day(int d):val(d){}
int val;
};
struct Month{
public:
static Month Jan() {return Month(1);}
//...
static Month Nov() {return Month(12);}
private:
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 d1(30, 3, 1995);//错误,不正确的类型
Date d2(Day(30), Month::Jan(), Year(1995));//错误,不正确的类型
Date d3(Month::Jan(), Day(30), Year(1995));//ok,类型正确


示例2:限制类型上的操作,例如使用const

if (a * b = c) //如果以const 修饰operator *的返回类型,这里会报错


示例3:消除客户的资源管理责任

InvestMent *createInvestment(); //客户有可能没有指针或者删了再次同一指针
std::tr1::shared_ptr<Investment> createInvestment();//强迫客户将返回值存储于一个tr1::shared_ptr内
std::tr1::shared_ptr<Investment> createInvestmnet()
{
std::tr1::shared_ptr<Investment> retVal(static_cast<Investment *>(0), getRidOfInvestment);
retVal = …; //令retVal指向正确对象
return retVal;
}


经验4:tr1::shared_ptr支持定制型删除器(custom delete)。这可防范DLL问题,可被用来自动解除互斥锁(mutexes)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐