当我在C++中将一个类放在一起时,我几乎总是会做一些事情.
1)虚拟析构函数2)复制构造函数和赋值运算符(我根据名为Copy()的私有函数实现它们,或者将它们声明为私有,从而明确禁止编译器自动生成它们).
你发现什么东西几乎总是有用的?
奇怪的是,这里的大多数建议都是我特别不做的事情.
除非我专门设计它才能继承,否则我不会将dtors设为虚拟.它增加了很多开销并且阻止了自动内联,这很糟糕,因为大多数dtors都是空的(并且很少有类受益于继承)
除非默认设置不起作用,否则我不会复制ctor/assignment op,如果不能,我可能要重新考虑设计.请记住,在字符串和向量之间,几乎没有理由再调用new.创建与默认版本相同的复制文件几乎肯定会降低效率.
我不添加字符串强制转换.它会引起太多问题,在这些问题中,无意中调用了强制转换.最好添加ToString()方法.
我不添加朋友oper <<,因为朋友是邪恶和凌乱的.最好添加一个Display(ostream)方法.那么oper <<可以称之为,而不需要成为朋友.事实上,你可以使oper <<模板函数调用Display(),而不必再担心它.
我发现打开gcc标志-Wall
,-Werror
和(这是有趣的)-Weffc++
帮助抓住了很多潜在的问题.从gcc手册页:
-Weffc++ (C++ only) Warn about violations of the following style guidelines from Scott Meyers’ Effective C++ book: · Item 11: Define a copy constructor and an assignment operator for classes with dynamically allocated memory. · Item 12: Prefer initialization to assignment in constructors. · Item 14: Make destructors virtual in base classes. · Item 15: Have "operator=" return a reference to *this. · Item 23: Don’t try to return a reference when you must return an object. and about violations of the following style guidelines from Scott Meyers’ More Effective C++ book: · Item 6: Distinguish between prefix and postfix forms of incre- ment and decrement operators. · Item 7: Never overload "&&", "??", or ",". If you use this option, you should be aware that the standard library headers do not obey all of these guidelines; you can use grep -v to filter out those warnings.