1.尽量以const,enum,inline替换#define
1 2 3 4 5 6 7 class Foo { private : static const int NUM = 5 ; } const int Foo::NUM;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 char grerting[] = "hello" ;char * p = grerting; const char * p = grerting;char * const p = grerting;const char * const p = grerting; std::vector<int > vec;const std::vector<int >::iterator iterator = vec.begin (); *iterator = 0 ; ++iterator; std::vector<int >::const_iterator iterator = vec.begin (); *iterator = 0 ; ++iterator;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 class Text { public : const char & operator [](std::size_t position) const { return text[position]; } char & operator [](std::size_t position){ return const_cast <char &>( static_cast <const Text&>(*this )[position]); } private : std::string text; };class Text { public : Text (std::string str):text (str){}; Text (std::string str){ text = str; }; private : std::string text; };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class FileSystem { };FileSystem& tfs () { static FileSystem tfs; return tfs; }class Directory { }; Directory::Directory (params){ std::size_t disks = tfs ().numDisks (); }Directory& tempDir () { static Directory td; return td; }
2.可禁止使用copy构造函数或copy assignment操作符,使其私有并只作声明
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 class HomeForSale { public : ... private : HomeForSale (const HomeForSale &); HomeForSale& operator =(const HomeForSale&); }class Uncopyable { protected : Uncopyable (){}; ~Uncopyable (){}; private : Uncopyable (const Uncopyable &); Uncopyable& operator =(const Uncopyable&); }class HomeForSale : private Uncopyable{ ... } HomeForSale home;HomeForSale new_home (home) ; HomeForSale new_home_assign; new_home_assign = home;
3.带多态性质的基类应该声明一个virtual析构函数,如果class带有任何virtual函数,都应拥有一个virtual析构函数
否则调用delete时,删除由base class指针指向的derived class,derived class的析构函数不会被执行,仅执行base class的析构函数
1 2 3 4 5 6 7 8 9 10 class TimeKeeper { public : TimeKeeper (); virtual ~TimeKeeper (); ... } TimeKeeper *ptk = getTimeKeeper (); ...delete ptk;
4.令operator=返回一个reference to this指针
1 2 3 4 5 6 7 8 class TimeKeeper { public : TimeKeeper& operator =(const TimeKeeper& rhs){ this .name = rhs.name; ... return *this ; } }
5.