C++

基础

1. 基本语法和数据类型

C++是一种静态类型的编程语言,支持多种数据类型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main() {
// 基本数据类型
int a = 10;
float b = 3.14;
double c = 3.1415926;
char d = 'A';
bool e = true;

// 输出数据类型大小
cout << "int size: " << sizeof(int) << " bytes" << endl;
cout << "float size: " << sizeof(float) << " bytes" << endl;
cout << "double size: " << sizeof(double) << " bytes" << endl;
cout << "char size: " << sizeof(char) << " bytes" << endl;
cout << "bool size: " << sizeof(bool) << " bytes" << endl;

return 0;
}

2. 控制结构

条件语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main() {
int score = 85;

if (score >= 90) {
cout << "优秀" << endl;
} else if (score >= 80) {
cout << "良好" << endl;
} else if (score >= 60) {
cout << "及格" << endl;
} else {
cout << "不及格" << endl;
}

return 0;
}

循环结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

int main() {
// for循环
cout << "For循环: " << endl;
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
cout << endl;

// while循环
cout << "While循环: " << endl;
int j = 0;
while (j < 5) {
cout << j << " ";
j++;
}
cout << endl;

return 0;
}

3. 函数

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
#include <iostream>
#include <cmath>
using namespace std;

// 函数声明
int add(int a, int b);
double areaOfCircle(double radius);

int main() {
int sum = add(3, 5);
cout << "3 + 5 = " << sum << endl;

double radius = 5.0;
double area = areaOfCircle(radius);
cout << "半径为" << radius << "的圆面积为: " << area << endl;

return 0;
}

// 函数定义
int add(int a, int b) {
return a + b;
}

double areaOfCircle(double radius) {
return M_PI * radius * radius;
}

4. 数组和字符串

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
using namespace std;

int main() {
// 数组
int numbers[5] = {1, 2, 3, 4, 5};
cout << "数组元素: " << endl;
for (int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
cout << endl;

// 字符串
string str1 = "Hello";
string str2 = " World";
string str3 = str1 + str2;

cout << "拼接后的字符串: " << str3 << endl;
cout << "字符串长度: " << str3.length() << endl;

return 0;
}

5. 指针和引用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;

int main() {
// 指针
int x = 10;
int* ptr = &x;

cout << "x的值: " << x << endl;
cout << "x的地址: " << &x << endl;
cout << "指针ptr的值: " << ptr << endl;
cout << "指针ptr指向的值: " << *ptr << endl;

// 引用
int& ref = x;
ref = 20;

cout << "修改引用后x的值: " << x << endl;
cout << "引用ref的值: " << ref << endl;

return 0;
}

核心

1. 面向对象编程

类和对象

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <string>
using namespace std;

// 类定义
class Student {
private:
string name;
int age;
float score;

public:
// 构造函数
Student(string n, int a, float s) {
name = n;
age = a;
score = s;
}

// 成员函数
void display() {
cout << "姓名: " << name << endl;
cout << "年龄: " << age << endl;
cout << "分数: " << score << endl;
}

// setter和getter
void setScore(float s) {
score = s;
}

float getScore() {
return score;
}
};

int main() {
// 创建对象
Student stu("张三", 20, 85.5);

// 调用成员函数
stu.display();

// 修改分数
stu.setScore(90.0);
cout << "修改后的分数: " << stu.getScore() << endl;

return 0;
}

继承

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <string>
using namespace std;

// 基类
class Person {
protected:
string name;
int age;

public:
Person(string n, int a) {
name = n;
age = a;
}

void display() {
cout << "姓名: " << name << endl;
cout << "年龄: " << age << endl;
}
};

// 派生类
class Employee : public Person {
private:
string company;
float salary;

public:
Employee(string n, int a, string c, float s) : Person(n, a) {
company = c;
salary = s;
}

void display() {
Person::display();
cout << "公司: " << company << endl;
cout << "工资: " << salary << endl;
}
};

int main() {
Employee emp("李四", 30, "ABC公司", 5000.0);
emp.display();

return 0;
}

多态

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
#include <string>
using namespace std;

// 基类
class Shape {
public:
// 虚函数
virtual void draw() {
cout << "绘制形状" << endl;
}

// 纯虚函数
virtual double area() = 0;
};

// 派生类 - 矩形
class Rectangle : public Shape {
private:
double width;
double height;

public:
Rectangle(double w, double h) {
width = w;
height = h;
}

void draw() override {
cout << "绘制矩形" << endl;
}

double area() override {
return width * height;
}
};

// 派生类 - 圆形
class Circle : public Shape {
private:
double radius;

public:
Circle(double r) {
radius = r;
}

void draw() override {
cout << "绘制圆形" << endl;
}

double area() override {
return M_PI * radius * radius;
}
};

int main() {
Shape* shapes[2];
shapes[0] = new Rectangle(5.0, 3.0);
shapes[1] = new Circle(4.0);

for (int i = 0; i < 2; i++) {
shapes[i]->draw();
cout << "面积: " << shapes[i]->area() << endl;
delete shapes[i];
}

return 0;
}

2. 模板

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
using namespace std;

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

// 类模板
template <typename T>
class Stack {
private:
T* data;
int top;
int capacity;

public:
Stack(int size) {
capacity = size;
data = new T[capacity];
top = -1;
}

~Stack() {
delete[] data;
}

void push(T value) {
if (top < capacity - 1) {
data[++top] = value;
}
}

T pop() {
if (top >= 0) {
return data[top--];
}
return T();
}

bool isEmpty() {
return top == -1;
}
};

int main() {
// 使用函数模板
cout << "max(3, 5): " << maxValue(3, 5) << endl;
cout << "max(3.14, 2.71): " << maxValue(3.14, 2.71) << endl;

// 使用类模板
Stack<int> intStack(5);
intStack.push(1);
intStack.push(2);
intStack.push(3);

cout << "栈弹出元素: " << endl;
while (!intStack.isEmpty()) {
cout << intStack.pop() << " ";
}
cout << endl;

return 0;
}

3. 标准库

STL 容器

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <set>
using namespace std;

int main() {
// 向量
vector<int> vec = {1, 2, 3, 4, 5};
cout << "向量元素: " << endl;
for (int num : vec) {
cout << num << " ";
}
cout << endl;

// 列表
list<int> lst = {10, 20, 30, 40, 50};
cout << "列表元素: " << endl;
for (int num : lst) {
cout << num << " ";
}
cout << endl;

// 映射
map<string, int> scores;
scores["张三"] = 85;
scores["李四"] = 90;
scores["王五"] = 75;

cout << "映射元素: " << endl;
for (auto& pair : scores) {
cout << pair.first << ": " << pair.second << endl;
}

// 集合
set<int> nums = {5, 2, 8, 1, 9};
cout << "集合元素: " << endl;
for (int num : nums) {
cout << num << " ";
}
cout << endl;

return 0;
}

STL 算法

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
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;

int main() {
vector<int> nums = {5, 2, 8, 1, 9, 3, 7, 4, 6};

// 排序
sort(nums.begin(), nums.end());
cout << "排序后: " << endl;
for (int num : nums) {
cout << num << " ";
}
cout << endl;

// 反转
reverse(nums.begin(), nums.end());
cout << "反转后: " << endl;
for (int num : nums) {
cout << num << " ";
}
cout << endl;

// 查找
int target = 5;
auto it = find(nums.begin(), nums.end(), target);
if (it != nums.end()) {
cout << "找到目标值 " << target << ",位置: " << distance(nums.begin(), it) << endl;
} else {
cout << "未找到目标值 " << target << endl;
}

// 累加
int sum = accumulate(nums.begin(), nums.end(), 0);
cout << "数组元素之和: " << sum << endl;

return 0;
}

进阶

1. 异常处理

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
#include <iostream>
#include <string>
using namespace std;

int divide(int a, int b) {
if (b == 0) {
throw string("除数不能为零");
}
return a / b;
}

int main() {
try {
int result = divide(10, 2);
cout << "10 / 2 = " << result << endl;

result = divide(10, 0);
cout << "10 / 0 = " << result << endl;
} catch (string& e) {
cout << "异常捕获: " << e << endl;
} catch (...) {
cout << "捕获到未知异常" << endl;
}

return 0;
}

2. 内存管理

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
#include <iostream>
using namespace std;

int main() {
// 动态分配单个变量
int* ptr1 = new int;
*ptr1 = 10;
cout << "动态分配的整数: " << *ptr1 << endl;
delete ptr1;

// 动态分配数组
int* ptr2 = new int[5];
for (int i = 0; i < 5; i++) {
ptr2[i] = i * 2;
}

cout << "动态分配的数组: " << endl;
for (int i = 0; i < 5; i++) {
cout << ptr2[i] << " ";
}
cout << endl;

delete[] ptr2;

return 0;
}

3. 高级特性

智能指针

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <memory>
using namespace std;

class MyClass {
public:
MyClass(int value) : data(value) {
cout << "构造函数被调用,data = " << data << endl;
}

~MyClass() {
cout << "析构函数被调用,data = " << data << endl;
}

void display() {
cout << "data = " << data << endl;
}

private:
int data;
};

int main() {
// unique_ptr
cout << "=== unique_ptr ===" << endl;
unique_ptr<MyClass> up1 = make_unique<MyClass>(10);
up1->display();

// shared_ptr
cout << "=== shared_ptr ===" << endl;
shared_ptr<MyClass> sp1 = make_shared<MyClass>(20);
shared_ptr<MyClass> sp2 = sp1;

cout << "引用计数: " << sp1.use_count() << endl;
sp1->display();
sp2->display();

// weak_ptr
cout << "=== weak_ptr ===" << endl;
weak_ptr<MyClass> wp = sp1;
if (auto sp3 = wp.lock()) {
sp3->display();
}

return 0;
}

Lambda 表达式

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
29
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
vector<int> nums = {1, 2, 3, 4, 5};

// 使用Lambda表达式排序
sort(nums.begin(), nums.end(), [](int a, int b) {
return a > b;
});

cout << "降序排序后: " << endl;
for (int num : nums) {
cout << num << " ";
}
cout << endl;

// 使用Lambda表达式作为函数对象
int multiplier = 2;
auto multiply = [multiplier](int x) {
return x * multiplier;
};

cout << "5 * " << multiplier << " = " << multiply(5) << endl;

return 0;
}

右值引用和移动语义

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>
#include <string>
using namespace std;

class MyString {
private:
char* data;
size_t length;

public:
// 构造函数
MyString(const char* str) {
length = strlen(str);
data = new char[length + 1];
strcpy(data, str);
cout << "构造函数: " << data << endl;
}

// 拷贝构造函数
MyString(const MyString& other) {
length = other.length;
data = new char[length + 1];
strcpy(data, other.data);
cout << "拷贝构造函数: " << data << endl;
}

// 移动构造函数
MyString(MyString&& other) noexcept {
length = other.length;
data = other.data;
other.data = nullptr;
other.length = 0;
cout << "移动构造函数: " << data << endl;
}

// 析构函数
~MyString() {
if (data != nullptr) {
cout << "析构函数: " << data << endl;
delete[] data;
}
}

// 获取字符串
const char* getString() const {
return data;
}
};

MyString createString() {
return MyString("Hello World");
}

int main() {
cout << "=== 创建临时对象 ===" << endl;
MyString str1 = createString();

cout << "=== 拷贝构造 ===" << endl;
MyString str2 = str1;

cout << "=== 移动构造 ===" << endl;
MyString str3 = move(str1);

return 0;
}

4. 多线程编程

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
using namespace std;

mutex mtx;
int counter = 0;

void increment(int iterations) {
for (int i = 0; i < iterations; i++) {
lock_guard<mutex> lock(mtx);
counter++;
}
}

int main() {
const int numThreads = 4;
const int iterationsPerThread = 100000;

vector<thread> threads;

// 创建线程
for (int i = 0; i < numThreads; i++) {
threads.push_back(thread(increment, iterationsPerThread));
}

// 等待所有线程完成
for (auto& t : threads) {
t.join();
}

cout << "最终计数器值: " << counter << endl;
cout << "预期值: " << numThreads * iterationsPerThread << endl;

return 0;
}

## 高级进阶

### 1. C++ 标准新特性

#### C++11 主要特性

```cpp
#include <iostream>
#include <vector>
#include <functional>
using namespace std;

// 自动类型推导
auto sum(int a, int b) -> int {
return a + b;
}

// nullptr
void func(int* p) {
cout << "指针版本" << endl;
}

void func(int n) {
cout << "整数版本" << endl;
}

// 范围for循环
void printVector(const vector<int>& vec) {
for (int num : vec) {
cout << num << " ";
}
cout << endl;
}

// 智能指针已经在前面介绍过

int main() {
// auto类型推导
auto x = 10;
auto y = 3.14;
auto z = "Hello";

cout << "x: " << x << ", 类型: int" << endl;
cout << "y: " << y << ", 类型: double" << endl;
cout << "z: " << z << ", 类型: const char*" << endl;

// nullptr
func(nullptr); // 调用指针版本
func(0); // 调用整数版本

// 范围for循环
vector<int> nums = {1, 2, 3, 4, 5};
printVector(nums);

// Lambda表达式已经在前面介绍过

return 0;
}

C++14/17/20 主要特性

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <vector>
#include <optional>
#include <variant>
#include <any>
#include <string_view>
#include <algorithm>
using namespace std;

int main() {
// C++14: 泛型Lambda
auto genericLambda = [](auto a, auto b) {
return a + b;
};

cout << "genericLambda(1, 2): " << genericLambda(1, 2) << endl;
cout << "genericLambda(3.14, 2.71): " << genericLambda(3.14, 2.71) << endl;

// C++17: 结构化绑定
vector<pair<string, int>> students = {"张三", 20, {"李四", 21}, {"王五", 22}};
for (auto& [name, age] : students) {
cout << "姓名: " << name << ", 年龄: " << age << endl;
}

// C++17: if constexpr
auto printType = [](auto value) {
if constexpr (is_integral_v<decltype(value)>) {
cout << "整数类型: " << value << endl;
} else if constexpr (is_floating_point_v<decltype(value)>) {
cout << "浮点类型: " << value << endl;
} else {
cout << "其他类型" << endl;
}
};

printType(42);
printType(3.14);

// C++17: optional
optional<int> maybeValue = 10;
if (maybeValue) {
cout << "Optional值: " << *maybeValue << endl;
}

// C++17: variant
variant<int, double, string> var;
var = 10;
var = 3.14;
var = "Hello";

// C++17: any
any a = 10;
a = 3.14;
a = "Hello";

// C++17: string_view
string_view sv = "Hello World";
cout << "string_view: " << sv << endl;
cout << "长度: " << sv.size() << endl;

return 0;
}

2. 设计模式在 C++中的应用

单例模式

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <mutex>
using namespace std;

class Singleton {
private:
static Singleton* instance;
static mutex mtx;

// 私有构造函数
Singleton() {
cout << "单例对象创建" << endl;
}

// 私有拷贝构造函数
Singleton(const Singleton&) = delete;

// 私有赋值操作符
Singleton& operator=(const Singleton&) = delete;

public:
static Singleton* getInstance() {
if (instance == nullptr) {
lock_guard<mutex> lock(mtx);
if (instance == nullptr) {
instance = new Singleton();
}
}
return instance;
}

void showMessage() {
cout << "Hello from Singleton!" << endl;
}

// 可选:添加销毁函数
static void destroyInstance() {
if (instance != nullptr) {
delete instance;
instance = nullptr;
}
}
};

// 静态成员初始化
Singleton* Singleton::instance = nullptr;
mutex Singleton::mtx;

int main() {
Singleton* s1 = Singleton::getInstance();
Singleton* s2 = Singleton::getInstance();

cout << "s1地址: " << s1 << endl;
cout << "s2地址: " << s2 << endl;

s1->showMessage();
s2->showMessage();

Singleton::destroyInstance();

return 0;
}

工厂模式

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <string>
#include <memory>
using namespace std;

// 产品接口
class Shape {
public:
virtual ~Shape() = default;
virtual void draw() const = 0;
};

// 具体产品
class Circle : public Shape {
public:
void draw() const override {
cout << "绘制圆形" << endl;
}
};

class Rectangle : public Shape {
public:
void draw() const override {
cout << "绘制矩形" << endl;
}
};

class Triangle : public Shape {
public:
void draw() const override {
cout << "绘制三角形" << endl;
}
};

// 工厂类
class ShapeFactory {
public:
enum ShapeType {
CIRCLE,
RECTANGLE,
TRIANGLE
};

unique_ptr<Shape> createShape(ShapeType type) {
switch (type) {
case CIRCLE:
return make_unique<Circle>();
case RECTANGLE:
return make_unique<Rectangle>();
case TRIANGLE:
return make_unique<Triangle>();
default:
throw invalid_argument("未知形状类型");
}
}
};

int main() {
ShapeFactory factory;

auto circle = factory.createShape(ShapeFactory::CIRCLE);
auto rectangle = factory.createShape(ShapeFactory::RECTANGLE);
auto triangle = factory.createShape(ShapeFactory::TRIANGLE);

circle->draw();
rectangle->draw();
triangle->draw();

return 0;
}

3. 模板元编程

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <type_traits>
using namespace std;

// 编译期计算阶乘
template <unsigned int N>
struct Factorial {
static constexpr unsigned int value = N * Factorial<N - 1>::value;
};

// 模板特化作为终止条件
template <>
struct Factorial<0> {
static constexpr unsigned int value = 1;
};

// 类型转换模板
template <typename T, typename U>
struct IsSameType {
static constexpr bool value = false;
};

template <typename T>
struct IsSameType<T, T> {
static constexpr bool value = true;
};

// 编译期条件判断
template <bool B, typename T, typename F>
struct Conditional {
using type = T;
};

template <typename T, typename F>
struct Conditional<false, T, F> {
using type = F;
};

int main() {
// 编译期阶乘计算
constexpr unsigned int fact5 = Factorial<5>::value;
cout << "5! = " << fact5 << endl;

// 类型判断
cout << "int 和 int 是否相同: " << IsSameType<int, int>::value << endl;
cout << "int 和 double 是否相同: " << IsSameType<int, double>::value << endl;

// 条件类型选择
using Type1 = typename Conditional<true, int, double>::type;
using Type2 = typename Conditional<false, int, double>::type;

cout << "Type1 是否为 int: " << IsSameType<Type1, int>::value << endl;
cout << "Type2 是否为 double: " << IsSameType<Type2, double>::value << endl;

return 0;
}

4. 性能优化技巧

内存对齐

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
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <cstddef>
using namespace std;

// 未对齐的结构体
struct UnalignedStruct {
char c;
int i;
double d;
};

// 手动对齐的结构体
struct AlignedStruct {
double d;
int i;
char c;
};

// 使用alignas指定对齐
struct alignas(16) Aligned16Struct {
char c;
int i;
double d;
};

int main() {
cout << "UnalignedStruct 大小: " << sizeof(UnalignedStruct) << endl;
cout << "UnalignedStruct 对齐: " << alignof(UnalignedStruct) << endl;

cout << "AlignedStruct 大小: " << sizeof(AlignedStruct) << endl;
cout << "AlignedStruct 对齐: " << alignof(AlignedStruct) << endl;

cout << "Aligned16Struct 大小: " << sizeof(Aligned16Struct) << endl;
cout << "Aligned16Struct 对齐: " << alignof(Aligned16Struct) << endl;

return 0;
}

移动语义优化

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <vector>
#include <string>
using namespace std;

class LargeObject {
private:
vector<int> data;

public:
LargeObject(size_t size) : data(size) {
cout << "构造函数: " << size << " 个元素" << endl;
}

// 拷贝构造函数
LargeObject(const LargeObject& other) : data(other.data) {
cout << "拷贝构造函数" << endl;
}

// 移动构造函数
LargeObject(LargeObject&& other) noexcept : data(move(other.data)) {
cout << "移动构造函数" << endl;
}

// 拷贝赋值操作符
LargeObject& operator=(const LargeObject& other) {
if (this != &other) {
data = other.data;
cout << "拷贝赋值操作符" << endl;
}
return *this;
}

// 移动赋值操作符
LargeObject& operator=(LargeObject&& other) noexcept {
if (this != &other) {
data = move(other.data);
cout << "移动赋值操作符" << endl;
}
return *this;
}

size_t size() const {
return data.size();
}
};

int main() {
vector<LargeObject> vec;

// 使用emplace_back避免拷贝
cout << "=== emplace_back ===" << endl;
vec.emplace_back(1000000);

// 使用移动语义
cout << "=== move ===" << endl;
LargeObject obj(2000000);
vec.push_back(move(obj));

cout << "容器大小: " << vec.size() << endl;

return 0;
}

5. 单元测试框架 - Google Test

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
29
30
31
32
33
34
35
36
37
38
39
#include <gtest/gtest.h>

// 要测试的函数
int add(int a, int b) {
return a + b;
}

int divide(int a, int b) {
if (b == 0) {
throw std::invalid_argument("除数不能为零");
}
return a / b;
}

// 测试用例
TEST(AddTest, PositiveNumbers) {
EXPECT_EQ(add(1, 2), 3);
EXPECT_EQ(add(10, 20), 30);
}

TEST(AddTest, NegativeNumbers) {
EXPECT_EQ(add(-1, -2), -3);
EXPECT_EQ(add(10, -5), 5);
}

TEST(DivideTest, NormalCase) {
EXPECT_EQ(divide(10, 2), 5);
EXPECT_EQ(divide(100, 10), 10);
}

TEST(DivideTest, DivideByZero) {
EXPECT_THROW(divide(10, 0), std::invalid_argument);
}

// 主函数
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

6. 常用 C++库介绍

Boost 库

Boost 是一个广泛使用的 C++库集合,提供了许多高质量的功能模块:

  • Boost.Asio: 网络和异步 I/O
  • Boost.SmartPtr: 智能指针(C++11 前的实现)
  • Boost.Thread: 线程库
  • Boost.FileSystem: 文件系统操作
  • Boost.Regex: 正则表达式
  • Boost.Serialization: 序列化
  • Boost.Graph: 图算法
  • Boost.Spirit: 解析器框架

Qt 库

Qt 是一个跨平台的 C++应用开发框架,主要用于 GUI 开发:

  • 丰富的 UI 组件
  • 信号槽机制
  • 跨平台支持
  • 网络编程
  • 数据库支持
  • 多媒体功能
  • 2D/3D 图形

STL 扩展库

  • absl: Google 的 C++公共库
  • folly: Facebook 的 C++库
  • eigen: 线性代数库
  • opencv: 计算机视觉库
  • pcl: 点云库
  • tensorflow: 机器学习库(C++ API)

7. C++内存模型

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <thread>
#include <atomic>
using namespace std;

atomic<int> sharedCounter(0);
int nonAtomicCounter(0);
mutex mtx;

void incrementAtomic(int iterations) {
for (int i = 0; i < iterations; i++) {
sharedCounter++;
}
}

void incrementNonAtomic(int iterations) {
for (int i = 0; i < iterations; i++) {
lock_guard<mutex> lock(mtx);
nonAtomicCounter++;
}
}

int main() {
const int numThreads = 4;
const int iterations = 100000;

vector<thread> threads;

// 测试原子变量
cout << "=== 测试原子变量 ===" << endl;
for (int i = 0; i < numThreads; i++) {
threads.emplace_back(incrementAtomic, iterations);
}

for (auto& t : threads) {
t.join();
}

cout << "原子变量结果: " << sharedCounter << endl;
cout << "预期结果: " << numThreads * iterations << endl;

// 测试非原子变量
cout << "=== 测试非原子变量 ===" << endl;
threads.clear();

for (int i = 0; i < numThreads; i++) {
threads.emplace_back(incrementNonAtomic, iterations);
}

for (auto& t : threads) {
t.join();
}

cout << "非原子变量结果: " << nonAtomicCounter << endl;
cout << "预期结果: " << numThreads * iterations << endl;

return 0;
}

8. 最佳实践和编码规范

命名规范

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
29
30
31
32
33
34
// 类名:大驼峰命名法
class MyClassName {
// 成员变量:小驼峰命名,前缀m_
int m_memberVariable;

public:
// 构造函数
MyClassName();

// 成员函数:小驼峰命名
void memberFunction();

// getter和setter
int getMemberVariable() const;
void setMemberVariable(int value);
};

// 函数名:小驼峰命名
void globalFunction();

// 常量:全大写,下划线分隔
const int MAX_VALUE = 100;

// 枚举:大驼峰命名
enum Color {
COLOR_RED,
COLOR_GREEN,
COLOR_BLUE
};

// 命名空间:全小写
namespace my_namespace {
// 内容
}

异常安全

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Resource {
private:
int* data;

public:
Resource(size_t size) : data(new int[size]) {
cout << "资源分配" << endl;
}

~Resource() {
delete[] data;
cout << "资源释放" << endl;
}

// 拷贝构造函数 - 深拷贝
Resource(const Resource& other) : data(new int[sizeof(other.data)/sizeof(int)]) {
cout << "深拷贝" << endl;
}

// 移动构造函数
Resource(Resource&& other) noexcept : data(other.data) {
other.data = nullptr;
cout << "移动构造" << endl;
}
};

// 异常安全的函数
void safeFunction() {
Resource r1(100);

// 如果这里抛出异常,r1会被正确销毁
vector<int> v(1000000000); // 可能抛出std::bad_alloc

Resource r2(200);
}

int main() {
try {
safeFunction();
} catch (const bad_alloc& e) {
cout << "捕获到内存分配异常: " << e.what() << endl;
}

return 0;
}

总结

C++是一种功能强大、灵活且高效的编程语言,它支持多种编程范式,包括面向对象、泛型编程和过程式编程。通过学习本文档中的内容,您应该已经掌握了 C++的基础知识、核心特性和高级技术。

要成为一名优秀的 C++程序员,建议:

  1. 深入理解 C++标准:关注 C++11/14/17/20 的新特性
  2. 学习优秀的代码:阅读开源项目的 C++代码
  3. 实践和项目:通过实际项目提升编程能力
  4. 性能优化:了解 C++的内存模型和性能特性
  5. 代码质量:遵循良好的编码规范和设计原则
  6. 持续学习:C++语言一直在发展,保持学习的热情

希望本文档对您的 C++学习之旅有所帮助!

1