条款01 :视C++为一个语言联邦

简单来说,讲了怎么理解C++编程时需要思考什么。多数时候C++对问题的解法是较为高级的C解法。主要提出了四个次语言及其相应的守则:C、Object-Oriented C++、Template C++、STL。

总的来说:C++高效编程守则需要视情况由此变化,取决于使用C++的哪一部分。

理解

C

int* arr = (int*)malloc(10 * sizeof(int)); // C 风格的内存分配
free(arr); // 必须手动释放

面向对象C++

类、封装、继承、多态、构造/析构函数

模板C++

泛型编程、编译时多态

// 泛型函数模板
template<typename T>
T max(T a, T b) { return (a > b) ? a : b; }

// 模板元编程(编译时计算)
template
struct Factorial {
static const int value = N * Factorial::value;
};
template <>
struct Factorial<0> { static const int value = 1; };

int main() {
int x = Factorial<5>::value; // 编译时计算 5! = 120
}

STL

容器、迭代器、算法、函数对象

#include <vector>
#include <algorithm>
#include <iostream>

int main() {
    std::vector<int> vec = {3, 1, 4, 1, 5}; // STL 容器
    std::sort(vec.begin(), vec.end());       // STL 算法
    for (auto it = vec.begin(); it != vec.end(); ++it) { // 迭代器
        std::cout << *it << " "; // 输出 1 1 3 4 5
    }
}

个人觉得这是编程思考逻辑的四个概括,或者说惯用法。理解这些规则间的差异能或多或少,在正确的场景选择正确的写法。这样一看,空口在这里是说不了什么的,丰富的经验才能让我更有发言权。

  • 在 STL 中使用迭代器和算法,而不是手写循环。
  • 在面向对象代码中优先使用智能指针而非裸指针。
  • 在模板编程中利用编译时计算而非运行时计算。