现代C++常用新特性

By pocaster

稍微整理下:

1. 自动类型推断 (auto)

auto 关键字允许编译器自动推断变量的类型,减少了代码冗余。

auto x = 42; // x 被推断为 int
auto y = 3.14; // y 被推断为 double

2. 基于范围的 for 循环

基于范围的 for 循环简化了遍历容器或数组的代码。

std::vector<int> v = {1, 2, 3, 4, 5};
for (const auto& elem : v) {
    std::cout << elem << std::endl;
}

3. nullptr

nullptr 是一个类型安全的空指针常量,用于替代 NULL0

int* ptr = nullptr;

4. 智能指针 (unique_ptr, shared_ptr, weak_ptr)

智能指针帮助管理动态内存,避免内存泄漏和悬空指针。

std::unique_ptr<int> p1(new int(42));
std::shared_ptr<int> p2 = std::make_shared<int>(42);

5. Lambda 表达式

Lambda 表达式允许在代码中定义匿名函数,简化了代码。

auto sum = [](int a, int b) { return a + b; };
std::cout << sum(2, 3) << std::endl; // 输出 5

6. std::move 和移动语义

移动语义允许资源的所有权从一个对象转移到另一个对象,避免了不必要的复制。

std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2 = std::move(v1); // v1 的资源被移动到 v2

7. 右值引用 (&&)

右值引用用于支持移动语义,允许对临时对象进行高效的操作。

void func(int&& x) {
    // x 是一个右值引用
}

8. constexpr

constexpr 允许在编译时计算表达式,提高性能。

constexpr int square(int x) {
    return x * x;
}
int array[square(3)] = {0}; // 数组大小为 9

9. std::thread 和多线程支持

现代C++引入了原生多线程支持,简化了多线程编程。

#include <iostream>
#include <thread>

void hello() {
    std::cout << "Hello from thread!" << std::endl;
}

int main() {
    std::thread t(hello);
    t.join();
    return 0;
}

10. 变长模板 (variadic templates)

变长模板允许函数或模板类接受任意数量的模板参数。

template<typename... Args>
void print(Args... args) {
    (std::cout << ... << args) << std::endl;
}

int main() {
    print(1, 2.5, "Hello");
    return 0;
}

11. std::optional

std::optional 表示一个可能包含值或可能为空的封装类型。

std::optional<int> getValue(bool condition) {
    if (condition) {
        return 42;
    } else {
        return std::nullopt;
    }
}

12. 结构化绑定 (structured bindings)

结构化绑定允许将多个变量绑定到一个结构体或元组的成员上。

std::pair<int, std::string> p = {1, "hello"};
auto [id, name] = p;
std::cout << id << " " << name << std::endl; // 输出 1 hello

13. std::variantstd::any

std::variant 可以存储多种类型的值,而 std::any 可以存储任意类型的值。

std::variant<int, std::string> v = "hello";
std::cout << std::get<std::string>(v) << std::endl; // 输出 hello

14. std::filesystem

std::filesystem 提供了操作文件系统的功能,如遍历目录、创建文件等。

#include <filesystem>
#include <iostream>

namespace fs = std::filesystem;

int main() {
    for (const auto& entry : fs::directory_iterator("./")) {
        std::cout << entry.path() << std::endl;
    }
    return 0;
}

15. 默认成员初始化器

可以在类定义中直接初始化成员变量,简化构造函数。

class MyClass {
public:
    int x = 10;
    std::string name = "default";
};
Tags: Gamedev Public