title: Effective C++ 学习笔记(四)设计与声明
date: 2021-03-15 09:20:42
tags:
参考书籍《Effective C++:改善程序与设计的 55 个具体做法(第三版)》
class Date { public: Date(int month, int day, int year); }
接口的不一致性对开发人员造成的心理和精神上的摩擦与争执。
任何接口如果要求客户必须记得做某些事情,就是有着“不正确使用”的倾向,因为客户可能会忘记做那件事。如下面例子,就要求用户使用智能指针,否则当用户忘记delete就会造成资源泄露
Investment* createInvestment();
cross-DLL problem:对象在动态连接程序库(DLL)中被 new创建,却在另一个 DLL 内被 delete销毁。在许多平台上,这一类“跨 DLL 之new/delete成对运用”会导致运行期错误。
struct Day { ... } struct Month { ... } struct Year { ... } class Date { public: Date(const Month& m, const Day& d, const Year& y); }
class Month { public: static Month Jan() {return Month(1);} static Month Feb() {return Month(2);} ... private: explicit Month(int m); }; Date d(Month::Mar(), ...);
除非有好理由,否则应该尽量令你的types的行为与内置types一致,提供行为一致的接口
在接口设计时,将返回指针接口用智能指针作为返回值,tr1::shared_ptr有一个特别好的性质是:它会自动使用它的“每个指针专属的删除器”,因而消除另一个潜在的客户错误:所谓的 "cross-DLL problem"。
std::tr1::shared_ptr<Investment> createInvestment();
■ 好的接口很容易被正确使用,不容易被误用。你应该在你的所有接口中努力达成这些性质。
■ “促进正确使用”的办法包括接口的一致性,以及与内置类型的行为兼容。
■ “阻止误用”的办法包括建立新类型、限制类型上的操作,束缚对象值,以及消除客户的资源管理责任。
■ tr1::shared_ptr支持定制型删除器(custom deleter)。这可防范DLL问题,可被用来自动解除互斥锁(mutexes;见条款14)等等。
■ Class的设计就是type的设计。在定义一个新type之前,请确定你已经考虑过本条款覆盖的所有讨论主题。
class Person { public: Person(); virtual ~Person(); ... private: std::string name; std::string address; }; class Student: public Person { public: Student(); ~Student(); ... private: std::string schoolName; std::string schoolAddress; }; bool validateStudent(Student s); // 当调用这个函数函数,会产生6次copy // 一次Student copy,一次Person copy,四次string copy
class Window { public: virtual void display() const; }; class WindowWithScrollBars: public Window { public: virtual void display() const; } void printNameAndDisplay(Window w) { w.display(); ... } WindowWithScrollBars wwsb; printNameAndDisplay(wwsb); // 将使用Window的display()!
bool vaildateStudent(const Student& s);
void printNameAndDisplay(const Window& w) { w.display(); } WindowWithScrollBars wwsb; printNameAndDisplay(wwsb); // ✔可以使用WindowWithScrollBars的display()
■ 尽量以pass-by-reference-to-const替换pass-by-value。前者通常比较高效,并可避免切割问题(slicing problem)。
■ 以上规则并不适用于内置类型,以及 STL 的迭代器和函数对象。对它们而言,pass-by-value往往比较适当。
返回reference对象前,可将对象在stack(局部变量)或heap(使用new)中构建。在stack(局部变量)中构建时,局部变量将在函数退出前被销毁,将返回一个已经被销毁的对象的引用!
const Rational& operator* (const Rational& lhs, const Rational& rhs) { Rational result(lhs.n * rhs.n, lhs.d * rhs.d); return result; }
在heap(使用new)中构建时,返回的对象极易被忘记delete!
const Rational& operator* (const Rational& lhs, const Rational& rhs) { Rational* result = new Rational(lhs.n * rhs.n, lhs.d * rhs.d); return result; }
■ 绝不要返回pointer或reference指向一个local stack对象,或返回reference指向一个heap-allocated对象,或返回pointer或reference指向一个local static对象而有可能同时需要多个这样的对象。条款 4 已经为“在单线程环境中合理返回 reference指向一个local static对象”提供了一份设计实例。
■ 切记将成员变量声明为private。这可赋予客户访问数据的一致性、可细微划分访问控制、允诺约束条件获得保证,并提供class作者以充分的实现弹性。
■ protected并不比public更具封装性。
namespace WebBrowserStuff{ class WebBrowser { ... }; void clearBrowser (WebBrowser& wb); }
// java class WebBrowserUtils { public static void clearBrowser (WebBrowser wb); };
■ 宁可拿non-member non-friend函数替换member函数。这样做可以增加封装性、包裹弹性(packaging flexibility)和机能扩充性。
class Rational { public: Rational (int numerator = 0, int denominator = 1); // non-explicit! int numerator() const; int denominator() const; const Rational operator* (const Rational& rhs) const; private: int numerator; int denominator; }; Rational oneHalf(1, 2); Rational result = oneHalf * 2; // 隐式转换:Rational result = oneHalf * Rational(2); // 调用 oneHalf.operator(Rational(2)); result = 2 * oneHalf; // 错误! // 尝试operator*(2, oneHalf);
class Rational { ... }; // non-number const Rational operator*(const Rational& lhs, const Rational& rhs) { return Rational(lhs.numerator()*rhs.numerator(), lhs.denominator()*rhs.denominator()); }
■ 切记将成员变量声明为private。这可赋予客户访问数据的一致性、可细微划分访问控制、允诺约束条件获得保证,并提供class作者以充分的实现弹性。
■ 如果你需要为某个函数的所有参数(包括被 this指针所指的那个隐喻参数)进行类型转换,那么这个函数必须是个non-member。
namespace std { template<typename T> void swap(T &a, T &b) { T temp(a); a = b; b = temp; } }
class WidgetImpl { private: int a, b, c; std::vector<double> v; }; class Widget { private: WidgetImpl* pImpl; };
class Widget { public: void swap(Widget& other) { using std::swap; swap(pImpl, other.pImpl); } }; namespace std { template<> void swap<Widget>(Widget& a, Widget& b) // 特化std::swap { a.swap(b); } }
namespace WidgetStuff{ template<typename T> class Widget { ... }; template<typename T> void swap(Widget<T>& a,Widget<T>& b) { a.swap(b); } }
■ 当std::swap对你的类型效率不高时,提供一个swap成员函数,并确定这个函数不抛出异常。
■ 如果你提供一个member swap,也该提供一个non-member swap用来调用前者。对于classes(而非templates),也请特化std::swap。
■ 调用swap时应针对std::swap使用using声明式,然后调用swap并且不带任何“命名空间资格修饰”。
■ 为“用户定义类型”进行std templates全特化是好的,但千万不要尝试在std内加入某些对std而言全新的东西。