资讯动态

第二章 C++11标准的改进(代码说明)

发布时间:2026/10/16 8:08:25 来源:尧图企业网站定制
// cpp11_demo.cpp// 编译: g -stdc11 -pthread cpp11_demo.cpp -o cpp11_demo// 运行: ./cpp11_demo#include iostream // 提供 std::cout 等输入输出#include vector // 提供 std::vector 动态数组#include string // 提供 std::string 字符串类#include algorithm // 提供 std::sort / all_of 等算法#include utility // 提供 std::move / std::forward#include thread // 提供 std::thread 线程类#include mutex // 提供 std::mutex / lock_guard#include memory // 提供智能指针#include unordered_map // 提供哈希表容器#include regex // 提供正则表达式#include chrono // 提供时间库#include random // 提供随机数库#include tuple // 提供 std::tuple 元组#include functional // 提供 std::function / bind#include array // 提供 std::array 固定数组#include forward_list // 提供 std::forward_list 单向链表#include initializer_list // 提供花括号列表支持// // 全局辅助// void print() {} // 可变参数模板递归终止templatetypename T, typename... Rest // 可变参数模板声明void print(T first, Rest... rest) { // 打印第一个参数std::cout first; // 输出当前参数print(rest...); // 递归处理剩余参数}class Buffer { // 演示移动语义的类int* data_; // 堆内存指针public:explicit Buffer(int v) : data_(new int(v)) {} // 构造函数Buffer(Buffer o) noexcept : data_(o.data_) { // 移动构造o.data_ nullptr; // 置空源对象指针}Buffer(const Buffer) delete; // 禁止拷贝构造~Buffer() { delete data_; } // 析构释放内存int value() const { return data_ ? *data_ : -1; } // 读取值};void target(int x) { std::cout 左值: x \n; } // 接收非常量左值void target(const int x) { std::cout const 左值: x \n; } // 接收常量左值void target(int x) { std::cout 右值: x \n; } // 接收右值templatetypename T // 万能引用模板void wrapper(T arg) { // 接收任意值类别target(std::forwardT(arg)); // 完美转发给 target}constexpr int square(int x) { return x * x; } // 编译期平方class A { // 演示委托构造public:A() : A(0) {} // 无参构造委托给 A(int)A(int x) : x_(x) {} // 有参构造int x_; // 成员};struct Base { Base(int) {} }; // 基类struct Derived : Base { using Base::Base; }; // 继承构造struct B12 { virtual void f() {} }; // 带虚函数的基类struct D12 : B12 { void f() override { std::cout 12. override ok\n; } }; // 重写class NoCopy { // 演示 default / deletepublic:NoCopy() default; // 默认构造NoCopy(const NoCopy) delete; // 禁止拷贝};templatetypename T, typename U // 尾置返回类型auto add(T a, U b) - decltype(a b) { // 返回类型由表达式推导return a b; // 返回相加结果}long double operator _km(long double x) { return x * 1000; } // 用户定义字面量int sum(std::initializer_listint nums) { // 接收花括号列表int s 0; // 累加器for (int n : nums) s n; // 遍历累加return s; // 返回总和}thread_local int counter 0; // 线程局部变量void worker(int id) { // 线程入口counter; // 自增本线程的 counterstd::cout 线程 id counter counter \n; // 输出}void safeFunc() noexcept {} // 承诺不抛异常class MoveOnly { // 只可移动的类public:MoveOnly() default; // 默认构造MoveOnly(const MoveOnly) delete; // 禁止拷贝MoveOnly(MoveOnly) noexcept default; // 移动构造};// // main// int main() { // 程序入口auto x 42; // 推导为 intauto d 3.14; // 推导为 doubleauto s std::string(hi); // 推导为 std::stringstd::cout 1. auto: x d s \n; // 输出std::vectorint v{1, 2, 3}; // 花括号初始化 vectorstd::cout 2. range-for: ; // 提示for (const auto n : v) std::cout n ; // 范围 for 遍历std::cout \n; // 换行Buffer b1(10); // 构造 b1Buffer b2(std::move(b1)); // 移动构造 b2std::cout 3. move: b2.value b2.value() \n; // 输出int lv 5; // 左值const int clv 6; // const 左值int rv 8; // 用于移动的右值std::cout 4. forward:\n; // 提示wrapper(lv); // 传左值wrapper(clv); // 传 const 左值wrapper(7); // 传字面量右值wrapper(std::move(rv)); // 传移动后的右值std::cout 5. variadic: ; // 提示print(1, -, 2.5, -, end); // 打印任意数量参数std::cout \n; // 换行int a{5}; // 花括号初始化 intstd::vectorint vv{1, 2, 3}; // 花括号初始化 vectorstruct Point { int x, y; }; // 局部结构体Point p{1, 2}; // 花括号聚合初始化std::cout 6. init: a vv.size() ( p.x , p.y )\n; // 输出int* ptr nullptr; // 空指针std::cout 7. nullptr: (ptr nullptr ? null : not null) \n; // 判断enum class Color { Red, Green, Blue }; // 强类型枚举std::cout 8. enum class: static_castint(Color::Red) \n; // 输出int arr[square(4)]; // 用 constexpr 决定数组大小std::cout 9. constexpr: size sizeof(arr)/sizeof(arr[0]) \n; // 输出std::vectorint lv2{3, 1, 2}; // 待排序std::sort(lv2.begin(), lv2.end(), [](int a, int b){ return a b; }); // lambda 降序std::cout 10. lambda: ; // 提示for (int n : lv2) std::cout n ; // 输出std::cout \n; // 换行std::cout 11. delegating ctor:\n; // 提示A objA; // 调用委托构造Derived objD(99); // 调用继承构造D12 dobj; // 派生类对象dobj.f(); // 调用重写函数NoCopy nc; (void)nc; // 默认构造成功std::cout 13. default/delete ok\n; // 提示static_assert(sizeof(int) 4, int must be 4 bytes); // 编译期断言std::cout 14. static_assert ok\n; // 提示std::string path R(C:\Users\test\file.txt); // 原始字符串std::cout 15. raw string: path \n; // 输出std::cout 16. thread_local:\n; // 提示std::thread t1(worker, 1); // 启动线程 1std::thread t2(worker, 2); // 启动线程 2t1.join(); // 等待线程 1t2.join(); // 等待线程 2long long big 123456789012345LL; // 64 位整数alignas(16) int alignedArr[4]; // 16 字节对齐数组alignedArr[0] 1; // 赋值std::cout 17. long long big alignof(double) alignof(double) \n; // 输出std::cout 18. trailing return: add(2, 3.5) \n; // 尾置返回std::unique_ptrint up(new int(5)); // 独占智能指针std::cout unique_ptr: *up \n; // 输出auto sp std::make_sharedint(10); // 共享智能指针std::weak_ptrint wp sp; // 弱引用std::cout shared_ptr: *sp use_count sp.use_count() weak expired wp.expired() \n; // 输出std::mutex mtx; // 互斥锁std::thread t([]{ // 新线程std::lock_guardstd::mutex lock(mtx); // 自动加锁std::cout in thread with lock\n; // 临界区输出});t.join(); // 等待线程结束std::unordered_mapstd::string, int m; // 哈希表m[apple] 3; // 插入m[banana] 5; // 插入std::cout unordered_map: ; // 提示for (const auto kv : m) // 遍历std::cout kv.first kv.second ; // 输出std::cout \n; // 换行std::regex re(R(\d)); // 数字正则std::smatch match; // 匹配结果std::string str abc123def; // 待匹配字符串if (std::regex_search(str, match, re)) // 搜索std::cout regex: match.str() \n; // 输出auto start std::chrono::steady_clock::now(); // 起始时间volatile int acc 0; // 防止优化for (int i 0; i 1000000; i) acc i; // 模拟耗时auto end std::chrono::steady_clock::now(); // 结束时间std::cout chrono ms: std::chrono::duration_caststd::chrono::milliseconds(end - start).count() \n; // 输出std::mt19937 gen(42); // 随机数引擎std::uniform_int_distributionint dist(1, 6); // 1~6 均匀分布std::cout random: ; // 提示for (int i 0; i 5; i) std::cout dist(gen) ; // 生成 5 个std::cout \n; // 换行auto tup std::make_tuple(1, 2.5, std::string(hi)); // 元组std::cout tuple: std::get0(tup) std::get1(tup) std::get2(tup) \n; // 输出std::functionint(int,int) f [](int a, int b){ return a b; }; // 可调用对象std::cout function: f(2, 3) \n; // 调用std::arrayint, 3 arr2{1, 2, 3}; // 固定数组std::forward_listint fl{1, 2, 3}; // 单向链表std::cout array size arr2.size() fl front fl.front() \n; // 输出std::vectorstd::pairint, std::string vp; // pair 容器vp.emplace_back(1, one); // 原地构造std::cout emplace: vp[0].second \n; // 输出std::vectorint v2{1, 2, 3, 4}; // 测试数据std::cout all_of: std::all_of(v2.begin(), v2.end(), [](int x){ return x 0; }) \n; // 判断std::cout initializer_list sum: sum({1, 2, 3, 4}) \n; // 求和std::cout to_string: std::to_string(42) \n; // 数值转字符串std::cout stoi: std::stoi(123) \n; // 字符串转数值std::cout 3.5_km 3.5_km m\n; // 用户字面量safeFunc(); // 调用 noexcept 函数std::cout noexcept(safeFunc()) noexcept(safeFunc()) \n; // 检查MoveOnly mo1; // 默认构造MoveOnly mo2(std::move(mo1)); // 移动构造(void)mo2; // 消除警告std::cout MoveOnly moved ok\n; // 提示return 0; // 正常返回}

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑