C++11新特性总汇

37 篇文章 0 订阅
26 篇文章 0 订阅

C++11新特性

1. 自动类型推导 (auto 和 decltype)

  • auto 允许编译器自动推断变量的类型。
  • decltype 提供了一种方式来获取表达式的类型。
int main() {
    auto i = 42; // 编译器推断 i 的类型为 int
    decltype(i) j = 0; // 使用 decltype 获取 i 的类型,并用它声明 j

    return 0;
}

2.初始化列表 (Uniform Initialization)

  • 可以使用花括号 {} 来初始化任何类型的对象,统一了初始化语法。
int main() {
    int a{5}; // 直接初始化
    std::vector<int> v{1, 2, 3, 4, 5}; // 容器初始化
    MyType obj{}; // 默认初始化
    MyType obj2{1, 2, 3}; // 调用构造函数

    return 0;
}

3. Lambda 表达式

  • 允许创建匿名函数对象,便于编写简洁的回调函数。
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> numbers{1, 2, 3, 4, 5};
    std::for_each(numbers.begin(), numbers.end(), [](int& n){ n *= 2; }); // 每个元素乘以2

    return 0;
}

4. 右值引用 (Rvalue References) 和移动语义 (Move Semantics)

  • 改进了资源管理,允许更高效的资源转移而非复制。
  • 允许函数接受和返回临时对象的引用,并通过移动语义优化资源转移,减少不必要的拷贝。
class MyClass {
public:
    MyClass() { /*...*/ }
    MyClass(const MyClass&) { /* 复制构造 */ }
    MyClass(MyClass&& other) noexcept { /* 移动构造 */ }
};

MyClass createInstance() {
    MyClass temp;
    return std::move(temp); // 返回一个右值引用,触发移动构造
}

int main() {
    MyClass instance = createInstance();
    return 0;
}

5. 智能指针 (std::unique_ptr, std::shared_ptr, std::weak_ptr)

  • 提供了更好的内存管理机制,减少内存泄漏的风险。
  • C++11引入了std::shared_ptrstd::unique_ptrstd::weak_ptr三种智能指针,用于自动管理动态分配的内存,避免内存泄漏和悬空指针。
#include <memory>

int main() {
    std::unique_ptr<int> uptr(new int(42)); // 独占所有权
    std::shared_ptr<int> sptr(new int(100)); // 共享所有权
    std::weak_ptr<int> wptr = sptr; // 不增加引用计数的弱引用

    return 0;
}

6. nullptr

  • nullptr是一个新的空指针常量,用于替代NULL0,提高了代码的可读性和类型安全性。
int main() {
    int* ptr = nullptr; // nullptr 是一种特殊的字面量,表示空指针
    if (!ptr) {
        // ...
    }

    return 0;
}

7. constexpr

  • 允许在编译时计算表达式,用于定义常量表达式或执行编译时的计算。
constexpr int factorial(int n) {
    return n <= 1 ? 1 : (n * factorial(n - 1));
}

int main() {
    constexpr int fact_of_5 = factorial(5); // 编译时常量
    static_assert(fact_of_5 == 120, "Factorial of 5 should be 120");

    return 0;
}

8. 委托构造函数 (Delegating Constructors)

  • 允许构造函数调用同一个类的其他构造函数。
class C {
public:
    C() : C(0) {} // 委托给带参数的构造函数
    C(int x) : data(x) {}
private:
    int data;
};

int main() {
    C c; // 使用默认构造函数,实际调用了 C(0)
    return 0;
}

9. 范围 for 循环 (Range-based for loop)

  • 简化遍历容器或其他序列的操作。
#include <vector>
#include <iostream>

int main() {
    std::vector<int> vec{1, 2, 3, 4, 5};
    for (const auto& elem : vec) { // 遍历 vector 中的元素
        std::cout << elem << ' ';
    }

    return 0;
}

10. 新的标准库功能

  • 包括新的算法、容器和其他工具,如 std::arraystd::forward_liststd::unordered_map/set 等。

11. 线程支持 (Concurrency Support)

  • 提供了线程库,包括 std::threadstd::mutexstd::future 等,使得多线程编程更为方便。
#include <thread>
#include <iostream>

void threadFunc() {
    std::cout << "Hello from another thread\n";
}

int main() {
    std::thread t(threadFunc);
    t.join(); // 等待线程结束
    return 0;
}

12. 强类型枚举

  • enum class 提供了强类型的枚举
enum class Color { Red, Green, Blue };
Color color = Color::Red;

13. 模板增强

  • 包括变参模板和外部模板
template<typename T>
void print(T arg) {
    std::cout << arg << std::endl;
}
template<typename T, typename... Args>
void print(T firstArg, Args... args) {
    std::cout << firstArg << ", ";
    print(args...); // 递归调用
}

14. 类型别名和类型推断

  • using 关键字提供了新的类型别名语法。
template<typename T>
using Vec = std::vector<T>;
Vec<int> vec = {1, 2, 3, 4, 5};

15. 属性规范

  • 使用双方括号语法提供编译器优化和检查。
[[noreturn]] void fail() {
    throw std::runtime_error("Failed!");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值