首页 > 代码库 > effective c++ 条款18 make interface easy to use correctly and hard to use incorrectly

effective c++ 条款18 make interface easy to use correctly and hard to use incorrectly

举一个容易犯错的例子

class Date{private:  int month;  int day;  int year;public:Date(int month,int day,int year){  this->month = month;  ...  }}//wrong exampleDate date(30,3,1995);//should be 3,30Date date(2,30,1995);//should be 3,30

使用类型可避免这个问题

class Month{  ... };class Day{  ... };class Year{  ... };class Date{private:  int month;  int day;  int year;public:Date(Month month,Day day,Year year){  this->month = month;  ...  }}

还有就是给客户资源要尽量自动回收。

参见 std::tr1::shared_ptr<> 

它能指定删除器。