C++11新特性
# C++11新特性
Created: March 19, 2024 1:38 PM
C++11引入了许多重要的新特性,使得C++编程更加方便、安全,同时也更高效。这些特性涵盖了语言本身、标准库以及编程范式。以下是一些关键的C++11新特性及示例:
# 1. 自动类型推断(auto
)
**auto
**关键字允许编译器自动推断变量的类型,使得代码更简洁。
auto x = 5; // x 被推断为 int
auto y = 1.5; // y 被推断为 double
1
2
2
# 2. 范围基于的for循环(Range-based for loop)
允许遍历容器而无需直接操作迭代器或计数器。
std::vector<int> vec = {1, 2, 3, 4, 5};
for (auto i : vec) {
std::cout << i << " ";
}
1
2
3
4
2
3
4
# 3. Lambda表达式
提供了定义匿名函数的能力,非常适合作为函数对象或闭包使用。
cppCopy code
std::vector<int> vec = {1, 2, 3, 4, 5};
std::for_each(vec.begin(), vec.end(), [](int val) {
std::cout << val << " ";
});
1
2
3
4
5
2
3
4
5
# 4. 智能指针(Smart Pointers)
std::unique_ptr
、std::shared_ptr
、**std::weak_ptr
**提供了自动的内存管理,帮助避免内存泄漏。
std::unique_ptr<int> ptr(new int(10));
std::cout << *ptr << std::endl; // 使用*操作符访问ptr指向的值
1
2
2
# 5. nullptr
提供了一个标准的方式来表示空指针。
int* ptr = nullptr;
if (ptr == nullptr) {
std::cout << "ptr is null" << std::endl;
}
1
2
3
4
2
3
4
# 6. 初始列表(Initializer lists)
允许用花括号**{}
**初始化任何对象。
std::vector<int> vec = {1, 2, 3, 4, 5};
1
# 7. 统一的初始化(Uniform initialization)
使用花括号**{}
**来初始化任何对象,消除了初始化方式的歧义。
int x{5};
std::vector<int> vec{1, 2, 3, 4, 5};
1
2
2
# 8. 委托构造函数(Delegating Constructors)
构造函数可以调用同一个类中的另一个构造函数,以避免代码重复。
class MyClass {
public:
MyClass() : MyClass(0) { }
MyClass(int value) : value(value) { }
private:
int value;
};
1
2
3
4
5
6
7
2
3
4
5
6
7
# 9. 继承构造函数(Inheriting Constructors)
子类可以继承父类的构造函数。
class Base {
public:
Base(int x) { }
};
class Derived : public Base {
using Base::Base; // 继承Base的构造函数
};
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 10. 类型别名(Type Aliases)
**using
**关键字提供了一种新的定义类型别名的方法。
using IntPtr = int*; // IntPtr现在是指向int的指针的别名
1
C++11的引入标志着C++编程范式的一大步进步,它不仅提高了编程效率,还增强了语言的表达能力和安全性。
编辑 (opens new window)