Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Các thay đổi mới trong C++11

C++11 (trước đây gọi C++0x) là bản cập nhật lớn nhất C++ kể từ C++98. Được ISO phê chuẩn 8/2011. Đưa C++ trở thành ngôn ngữ hiện đại hơn, an toàn và biểu đạt hơn.

Top 10 tính năng quan trọng nhất

1. auto - Type deduction

auto x = 42;           // int
auto& ref = x;         // int&
const auto& cref = x;  // const int&
auto ptr = new int(10); // int*

2. Range-based for loop

for (auto& elem : container) { ... }
for (const auto& elem : vec) { ... }
for (auto elem : vec) { ... } // copy

3. Lambda expressions

auto add = [](int a, int b) { return a + b; };
auto capture = [x, &y]() mutable { x++; y++; };

4. Smart pointers

#include 
auto p1 = std::make_unique(42);
auto p2 = std::make_shared("hello");
std::weak_ptr wp = p2; // Không tăng ref count

5. nullptr

int* p = nullptr; // Không convert ngầm sang int

6. enum class (Scoped enum)

enum class Color { Red, Green, Blue };
Color c = Color::Red; // Không leak tên

7. override / final

class Base { virtual void foo(); };
class Derived : Base {
    void foo() override; // Check compile-time
    void bar() final;    // Không override nữa
};

8. =delete / =default

class NonCopyable {
    NonCopyable(const NonCopyable&) = delete;
    NonCopyable& operator=(const NonCopyable&) = delete;
    NonCopyable() = default;
};

9. static_assert

static_assert(sizeof(int) == 4, "int phải 4 bytes");
static_assert(std::is_trivial_v, "T phải trivial");

10. Move semantics & Rvalue references

class Buffer {
    char* data;
    size_t size;
public:
    Buffer(Buffer&& other) noexcept 
        : data(other.data), size(other.size) {
        other.data = nullptr; other.size = 0;
    }
};

Các tính năng khác quan trọng

  • Initializer lists: {1,2,3} cho container
  • Variadic templates: template<typename... Args>
  • Uniform initialization: T x{val};
  • decltype: Lấy kiểu biểu thức
  • constexpr: Hàm/biến compile-time
  • Thread support: <thread>, <mutex>, <atomic>
  • New algorithms: all_of, any_of, none_of, iota
  • std::array, std::tuple, std::function
  • Right angle brackets: vector<vector<int>> (không cần space)

Tác động

C++11 thay đổi cách viết C++ cơ bản. Code C++11+ ngắn gọn, an toàn, hiệu năng hơn C++98 đáng kể. Nền tảng cho C++14/17/20/23.