跳到主要内容

C++11特性

Lambda 表达式

//使用 Lambda 表达式打印每个元素
std::for_each(nums.begin(), nums.end(), [](int num) {
std::cout << num << " "; // 输出 1 2 3 4 5
});

右值引用

C++11之前,当我们需要传递或返回对象时,通常会进行对象的复制,这对于某些资源密集型对象来说开销很大。
C++11引入了右值引用(&&)和移动语义,使得我们可以通过移动资源而不是复制资源来显著提升性能。
右值引用主要有两个重要的应用场景:移动语义和完美转发。
右值引用:右值引用是一种引用类型,它可以绑定到临时对象(右值)。右值引用的主要用途是实现移动语义。
移动语义:移动语义允许对象的资源(如内存、文件句柄等)通过"移动"的方式从一个对象转移到另一个对象,而不是通过复制,从而避免不必要的资源分配和释放。

基于范围的for循环

std::vector<int> nums = {1, 2, 3, 4, 5};
for (int num : nums) {
std::cout << num << " "; // 输出 1 2 3 4 5
}

多线程支持

  • std::thread类创建线程
  • std::mutex、std::timed_mutex、std::recursive_mutex与std::recursive_timed_mutex互斥量类
  • std::lock_guard、std::unique_lock(提供更多细节方法,但更占空间,效率比前者差一点)配合std::mutex,离开作用域自动释放互斥量
  • std::condition_variable条件变量类(有wait/notify_one/notify_all成员函数)
  • std::this_thread::sleep_for(std::chrono::milliseconds(900));//还有sleep_until
  • std::atomi原子操作类模板与std::memory_order(比较少用到)
  • std::call_once只调用一次,配合std::once_flag变量使用。一般用在单例模式
  • std::async与std::future、std::share_futrue
  • std::packaged_task任务打包
  • std::promise传入到线程,用于赋值。另一种方式获取值
#include <iostream>
#include <thread>
#include <mutex>
int nums = 0;
std::mutex mutex;
// 线程执行的函数
void threadFunction() {
std::lock_guard<std::mutex> lock(mutex);
nums++;
std::cout << "Hello from thread!" << std::endl;
}
int main() {
// 创建线程并执行
std::thread t1(threadFunction);
std::thread t2(threadFunction);
// 等待线程完成
t1.join();
t2.join();
return 0;
}

智能指针

  • shared_ptr:是一种共享式智能指针,多个指针可以同时共享对同一对象的拥有权。通过 std::make_shared 函数可以创建 std::shared_ptr 对象,如:
std::shared_ptr<int> ptr = std::make_shared<int>(42);
  • unique_ptr:是一种独占式智能指针,用于管理唯一的对象,确保只有一个指针可以访问该对象,通过 std::make_unique 函数可以创建 std::unique_ptr 对象,如:
std::unique_ptr<int> ptr = std::make_unique<int>(42);
  • weak_ptr:是一种弱引用智能指针,它可以解决 std::shared_ptr 的循环引用问题,std::weak_ptr 指向 std::shared_ptr 管理的对象,但不会增加引用计数。因此,当所有 std::shared_ptr 对象超出作用域后,即使还有 std::weak_ptr 对象存在,所管理的对象也会被销毁。通过 std::shared_ptr 的 std::weak_ptr 构造函数可以创建 std::weak_ptr 对象,如:
std::weak_ptr<int> weakPtr = sharedPtr;

constexpr

C++11 新标准规定,允许将变量声明为 constexpr 类型以便由编译器来验证变量的值是否是一个常量表达式。声明为 constexpr 的变量一定是一个常量,而且必须用常量表达式初始化:

constexpr int age = 23;
constexpr int get_age(){return 23;}
constexpr int age = get_age();