# 杂项

  1. explicit
    构造函数默认是隐式转换的,如果想要禁止隐式转换,可以使用 explicit 关键字修饰构造函数。
    比如
explicit
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>

class FileSize {
public:
// 构造函数:接受字节数
FileSize(long long bytes) : bytes_(bytes) {}

long long getBytes() const { return bytes_; }

private:
long long bytes_;
};

void deleteFileLargerThan(const FileSize& maxSize) {
std::cout << "Deleting files larger than " << maxSize.getBytes() << " bytes.\n";
// 实际逻辑省略...
}

int main() {
deleteFileLargerThan("100MB"); // 打错了!本想传字符串配置,但函数不接受 string
// "100MB" → const char* → bool(true) → long long(1) → FileSize(1)
// 变成:Deleting files larger than 1 bytes. 严重错误
}
  1. 回调函数
    回调函数是一种函数指针,它允许在运行时指定一个函数,并在某个事件发生时调用该函数。
    人话:一个被作为参数传递给另一个函数,并在 “合适的时候” 被调用的函数。
callback
1
2
3
4
5
#include <functional>

std::function<R(Args...)> cb;
// R: 返回类型
// Args...: 参数列表

std::function 能装什么?

  • 普通函数
callback
1
2
3
4
void greet() { std::cout << "Hello!\n"; }

std::function<void()> cb = greet;
cb(); // 输出 Hello!
  • Lambda 表达式
callback
1
2
3
4
5
int x = 42;
std::function<void()> cb = [x]() {
std::cout << "Captured x = " << x << "\n";
};
cb(); // 输出 Captured x = 42
  • 函数对象
  • 成员函数
  1. mutable std::mutex mtx_;
    mutable 关键字表示变量可以在常量函数中修改。
    如果没有 mutable,mtx_ 是普通成员变量,在 const 函数中,所有成员都被视为 const,调用 mtx_.lock () 会报错

  2. std::unique_lockstd::mutex lock(mtx_)
    进入时自动调用 mtx_.lock ()(当前线程获得锁),当 lock 变量离开作用域(比如函数返回、出 {}),会自动调用 mtx_.unlock ()

  3. lambda
    有点抽象,有空继续研究
    https://c.biancheng.net/view/bl1yvwy.html

  • 作为函数对象(Functor)替代手写类
lambda
1
2
3
4
5
6
7
8
struct IsEven {
bool operator()(int x) const { return x % 2 == 0; }
};

std::vector<int> v = {1,2,3,4,5};
auto it = std::find_if(v.begin(), v.end(), IsEven{});
// lambda写法
auto it = std::find_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; });
  • STL 算法的自定义谓词(最常用!)
lambda
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
std::vector<Person> people = {...};

// 按年龄降序
std::sort(people.begin(), people.end(),
[](const Person& a, const Person& b) {
return a.age > b.age;
});

// 删除所有空字符串
vec.erase(
std::remove_if(vec.begin(), vec.end(),
[](const std::string& s) { return s.empty(); }),
vec.end()
);

// 找第一个大于 10 的数
auto it = std::find_if(v.begin(), v.end(), [](int x) { return x > 10; });
  1. condition_variable
    不希望 FSM 的 worker 线程这样:
轮询
1
2
3
4
while (true) {
if (queue 空)
一直查(忙等)
}

condition_variable 的作用:

  • 队列空 → 工作线程睡觉
  • 有事件 → 唤醒工作线程
    写法:
condition_variable
1
cv.wait(lock, []{ return !queue.empty(); });
  1. atomic 库
    atomic<bool> 原子变量,线程安全的 bool

  2. 匿名函数

  3. workerThread + 队列 + 状态机

Edited on

Give me a cup of [coffee]~( ̄▽ ̄)~*

NoResponse WeChat Pay

WeChat Pay

NoResponse Alipay

Alipay

NoResponse PayPal

PayPal