您的位置:首页 > 其它

4.设计与声明

2016-03-12 21:08 246 查看

Item18:Make interfaces easy to use correctly and hard to use incorrectly.

shared_ptr定制删除器可以防范DLL问题(对象在一个DLL中创建,却在另一个DLL中销毁),自动解除互斥锁等。

Item19:Treat class design as type desing.

Item20:Prefer pass-by-reference-to-const to pass-by-value.

reference往往以指针实现,因此除了(当参数为内置类型,STL迭代器和函数对象时),pass-by-value比较适当。

Item21:Don’t try to return a reference when you must return an object.

不要返回pointer或reference指向一个local stack对象(离开作用域便失效)

不要返回reference指向一个heap_allocated对象(无法删除)

不要返回pointer或reference指向一个local static对象(对pointer或reference的值进行比较可能是指向同一个local static而导致永远为true)

Item22:Declare data members private.

Item23:Prefer non-member non-friend functions to member functions.

不会影响class原有的封装性。

Item24:Declare non-member functions when type conversions should apply to all parameters.

如运算符重载:

Rational r(1,2);
Rational r2=r*1;     //当*为成员时true
r2=1*r;     //此时*为成员则false


因为隐式转换只有当参数列于参数列表内时才会有资格执行。r2=1*r;此时1不在参数列表内,所以无法进行隐式转换。当*变为non-member function时可以。

Item25:Consider support for a non-throwing swap

当类使用pimpl(pointer to implementation)时,需要实现自己的swap以高效进行交换(直接交换成员指针而无需创建临时对象)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: