C++11:新特性(总结+实例)

C++11是C++语言的一个重要版本,引入了许多新的特性和语法改进,使得C++编程更加方便、高效和安全。下面是一些C++11的新特性和实例的详解。

1、自动类型推断(auto)
C++11引入了auto关键字,用于自动推断变量的类型。这样可以简化代码,减少类型重复。

auto x = 10; // x的类型被推断为int
auto y = 3.14; // y的类型被推断为double

2、范围for循环(range-based for loop)
范围for循环可以在遍历容器或数组时更加简洁和直观。

std::vector<int> nums = {1, 2, 3, 4, 5};

for (auto num : nums) {
    std::cout << num << " ";
}
// 输出:1 2 3 4 5

3、基于范围的循环支持迭代器
范围for循环也可以用于遍历支持迭代器的对象。

std::string str = "Hello, World!";

for (auto c : str) {
    std::cout << c << " ";
}
// 输出:H e l l o ,   W o r l d !

4、nullptr
nullptr是一个新的空指针常量,可以用于取代NULL或0,提高代码的可读性和类型安全性。

int* p = nullptr;

5、lambda表达式
lambda表达式允许我们在代码中定义匿名函数,简化了函数对象的使用。

std::vector<int> nums = {1, 2, 3, 4, 5};

std::for_each(nums.begin(), nums.end(), [](int num) {
    std::cout << num << " ";
});
// 输出:1 2 3 4 5

6、智能指针(smart pointers)
C++11引入了三种智能指针:shared_ptr、unique_ptr和weak_ptr,用于管理动态分配的内存,避免内存泄漏和悬空指针的问题。

std::shared_ptr<int> p1(new int(10));
std::unique_ptr<int> p2(new int(20));
std::weak_ptr<int> p3 = p1;

std::cout << *p1 << " " << *p2 << std::endl;
// 输出:10 20

7、原始字符串字面量(raw string literals)
原始字符串字面量可以用于在字符串中包含特殊字符,而无需进行转义。

std::string str = R"(C:\Windows\System32\)";
std::cout << str << std::endl;
// 输出:C:\Windows\System32\

8、强类型枚举(strongly-typed enum)
强类型枚举可以限制枚举类型的作用域,避免了枚举常量的命名冲突。

enum class Color { Red, Green, Blue };
enum class Size { Small, Medium, Large };

Color color = Color::Red;
Size size = Size::Medium;

9、空函数(nullptr_t)
空函数是一个新的类型nullptr_t,可以用于表示空函数指针。

void func(nullptr_t) {
    std::cout << "Null function pointer" << std::endl;
}

func(nullptr);
// 输出:Null function pointer

10、委托构造函数(delegating constructors)
委托构造函数允许一个构造函数调用另一个构造函数,减少了重复的代码。

class MyClass {
public:
    MyClass() : MyClass(0) {}
    MyClass(int x) : x_(x) {}

private:
    int x_;
};

以上是C++11的一些新特性和实例的详解,这些特性使得C++编程更加方便、高效和安全。学习和掌握这些特性可以提高代码的质量和开发效率。

猜你喜欢

转载自blog.csdn.net/bigger_belief/article/details/131815400