c## Explicit用法
防止隐式转换
比如
class MyClass {
explict MyClass(int x);
}
void some_func(MyClass Obj);
int main() {
some_func(10);//这个不work
some_func(MyClass(10)) //这个work
}
好处就是防止意外类型转换导致问题
注意只能单参数构造函数用
引用构造函数和移动构造函数的区别
// 拷贝构造函数
String(const String& other) {
length = other.length;
data = new char[length + 1];
strcpy(data, other.data);
std::cout << "Copy constructor called" << std::endl;
}
//const原因是不希望改变other的值
//移动构造函数
String(String&& other) noexcept {
}
//右值引用,是可以改变的other,因为std::move()是要窃取资源的所以不是const
常量 const的用法
口诀:在C++中,const 关键字修饰的是它左侧的内容。
如果 const 在最左边,那么它修饰右侧的内容。
const int* 比如这个指针,代表指针指向的那个int的值不可以改变
int* const 代表指针本身不能改变指向
int value1 = 10, value2 = 20;
// const int*
const int* p1 = &value1;
p1 = &value2; // 正确:可以改变指针
// *p1 = 30; // 错误:不能通过 p1 修改值
// int* const
int* const p2 = &value1;
*p2 = 30; // 正确:可以通过 p2 修改值
// p2 = &value2; // 错误:不能改变指针
如果是
const int* const p1
那就是既不能改变指针,又不能改变指针指向的值
const int& x
代表你通过这个引用不能去改变原来的值,引用的本质是别名
int& const x
没有这个语法,因为引用本身已经是常量了
思考题:
const int x = 10;
const int& ref = x; // 可以创建对常量的引用
// int& nonConstRef = x; // 错误:不能用非常量引用绑定到常量
const int* ptr = &x; // 指向常量的指针
C++ 线程池
#include <mutex>
#include <condition_variable>
class ThreadPool {
public:
ThreadPool(size_t numThreads) {
//确保我同时只有4个线程在工作
for (size_t i = 0; i < numThreads; ++i) {
workers.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(queueMutex);
condition.wait(lock, [this] { return stop || !tasks.empty(); });
//当被唤醒的时候,把判断task queue
if (stop && tasks.empty()) {
return;
}
task = std::move(tasks.front());
tasks.pop();
}
//执行task
task();
}
});
}
}
template<class F>
void enqueue(F&& f) {
{
std::unique_lock<std::mutex> lock(queueMutex);
tasks.emplace(std::forward<F>(f));
}
condition.notify_one();
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queueMutex);
stop = true;
}
condition.notify_all();
for (std::thread &worker : workers) {
worker.join();
}
}
private:
//工作thread
std::vector<std::thread> workers;
//工作的tasks
std::queue<std::function<void()>> tasks;
//锁
std::mutex queueMutex;
std::condition_variable condition;
bool stop = false;
};
// 使用示例
int main() {
ThreadPool pool(4); // 创建4个工作线程
//在创立线程的初期,所有的线程都会进入condition_variable.wait()的状态
// 提交一些任务
for (int i = 0; i < 8; ++i) {
pool.enqueue([i] {
std::cout << "Task " << i << " is running on thread " << std::this_thread::get_id() << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Task " << i << " is done" << std::endl;
});
}
// 主线程等待一段时间,让任务有机会执行
std::this_thread::sleep_for(std::chrono::seconds(10));
return 0;
}