深入浅出C++11新特性详解
一、自动类型推导
1.1 auto关键字
// 传统迭代器声明
std::vector<int>::iterator it = vec.begin();
// C++11 auto推导
auto auto_it = vec.begin(); // 自动推导为vector<int>::iterator
1.2 decltype类型推导
int x = 5;
decltype(x) y = 10; // y的类型与x相同(int)
template<typename T, typename U>
auto add(T t, U u) -> decltype(t + u) {
return t + u;
}
二、现代化循环
2.1 基于范围的for循环
std::vector<int> nums{1,2,3,4,5};
// 传统遍历方式
for(std::vector<int>::iterator it = nums.begin();
it != nums.end(); ++it) {
std::cout << *it << " ";
}
// C++11范围遍历
for(auto& num : nums) {
std::cout << num << " ";
}
三、智能指针(内存管理革命)
3.1 unique_ptr
std::unique_ptr<int> p1(new int(5));
// std::unique_ptr<int> p2 = p1; // 错误:禁止拷贝
// 所有权转移
std::unique_ptr<int> p3 = std::move(p1);
3.2 shared_ptr与weak_ptr
class Node {
public:
std::shared_ptr<Node> next;
std::weak_ptr<Node> prev; // 防止循环引用
};
auto node1 = std::make_shared<Node>();
auto node2 = std::make_shared<Node>();
node1->next = node2;
node2->prev = node1;
四、移动语义与完美转发
4.1 右值引用
class StringWrapper {
public:
// 移动构造函数
StringWrapper(StringWrapper&& other) noexcept
: data_(other.data_), size_(other.size_) {
other.data_ = nullptr; // 转移资源所有权
}
private:
char* data_;
size_t size_;
};
4.2 完美转发
template<typename T>
void wrapper(T&& arg) {
worker(std::forward<T>(arg)); // 保持参数的值类别
}
五、Lambda表达式(函数式编程)
std::vector<int> numbers{3,1,4,1,5};
// 使用lambda进行排序
std::sort(numbers.begin(), numbers.end(),
[](int a, int b) { return a > b; });
// 捕获列表示例
int base = 10;
std::for_each(numbers.begin(), numbers.end(),
[base](int n) { std::cout << n + base << " "; });
六、编译期计算
6.1 constexpr
constexpr int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
int main() {
constexpr int fact5 = factorial(5); // 编译期计算120
int arr[fact5]; // 合法声明数组
}
七、模板增强
7.1 变长参数模板
template<typename... Args>
void printAll(Args... args) {
// 使用折叠表达式展开参数包
(std::cout << ... << args) << "\n";
}
printAll(1, "apple", 3.14); // 输出:1apple3.14
八、并发支持
8.1 原子操作
#include <atomic>
std::atomic<int> counter(0);
void increment() {
for(int i=0; i<100000; ++i) {
counter.fetch_add(1, std::memory_order_relaxed);
}
}
8.2 线程库
#include <thread>
#include <future>
auto future = std::async([](){ return 42; }); // 异步任务
std::cout << future.get(); // 输出42
std::thread t([](){
std::cout << "Hello from thread!\n";
});
t.join();
九、其他重要特性
9.1 强类型枚举
enum class Color : uint8_t { Red = 0xFF, Green = 0x00FF }; // 指定底层类型
Color c = Color::Red;
// int i = c; // 错误,禁止隐式转换
9.2 委托构造函数
class Circle {
public:
Circle() : Circle(1.0) {} // 委托构造函数
explicit Circle(double r) : radius(r) {}
private:
double radius;
};
专栏特色:
- 每个特性配套可编译的完整代码示例
- 对比传统C++实现与新特性的优劣
- 性能优化点特别标注(如移动语义对STL的影响)