Effective C++(Item 1-10)

Table of Contents

Item 1: View C++ as a federation of languages

  • C. C++仍然基于C。
  • Object-Oriented C++.
  • Template C++.
  • The STL.

Tings to Remember

  • 高效的C++编程规则依赖于你使用C++的哪部分。

Item 2: Prefer consts, enums, and inlines to #defines

当替换定值的 #define 时,有2种特殊情况。第一种是定值的指针,除了指针被声明为 const ,指针所指的内容同样也是定值的,需要写 const 两次如下:

const char * const authorName = "Scott Mayers";
// use string
const std::string authorName("Scott Mayers");

第二种特殊情况是class特定的定值.限制类的定值范围,它必须是成员并且确保定值只有一份拷贝,它必须是 static 成员:

class GamePlayer {
 private:
  static const int NumTurns = 5;  // const declaration
  int scores[NumTurns];
};

上面仅仅是声明,而不是它的定义。一般它的定义如下:

const int GamePlayer::NumTurns;  // definition

把这放在实现文件,而不是头文件中。因为初始值在它的声明处提供, 在定义处不允许提供初始值。

如果使用 enum 可以如下:

class GamePlayer {
 private:
  enum { NumTurns = 5 };
  int scores[NumTurns];
};

回到预编译,另外通常使用 #define 来实现类似函数的宏,可以不用产生函数调用的开销。如下的宏为例:

// call f with the maximum of a and b
#define CALL_WITH_MAX(a,b) f((a) > (b) ? (a) : (b))

如这样的宏有许多缺点。通过使用inline的模板函数,不但可以获得宏的所有效率,并且可以达到普通函数所有可预测的行为:

template<typename T>
inline void callWithMax(const T& a, const T& b)
// because we don't know what T is, we pass by reference const.
{
  f(a > b? a : b);
}

Tings to Remember

  • 对于简单的constants,优先使用const对象和enum,而不是#define.
  • 对于类似函数的宏,优先使用inline函数,而不是#define.

Item 3: Use const whenever possible

Tings to Remember

  • 声明const帮助编译器侦测使用错误.const能被应用到任何地方的对象,从函数参数,到返回类型,到整个成员函数.
  • 编译器强制bitwise constness,但是你应使用概念性的定值来编程.
  • 当const和非const成员函数有一致的内在实现.代码重复可以避免,通过非 const版本调用const版本.

Item 4: Make sure that objects are initialized before they're used

Tings to Remember

Item

Tings to Remember

Item

Tings to Remember

Item

Tings to Remember

Item

Tings to Remember

Item

Tings to Remember

Item

Tings to Remember

Item

Tings to Remember

Item

Tings to Remember

cc



Author: Shi Shougang

Created: 2015-03-05 Thu 23:21

Emacs 24.3.1 (Org mode 8.2.10)

Validate