C++11旨在提升代码的可读性、可维护性和性能。它引入了模块化支持、自动类型推断、控制流与函数式编程改进等特性,涵盖了基础类型与数据结构,如std::vector
、std::map
,以及控制流与函数式编程优化。C++11还以并发编程与线程基础,结合std::async
和std::future
,简化了异步操作。模板与泛型编程的增强,通过构造函数模板、常量模板和元编程工具如std::integral_constant
,提供了更强大的类型检查与功能选择能力。实战项目与案例分析展示了如何应用C++11特性构建高效应用,同时提供了陷阱分析与优化建议,助你安全地运用新特性。
基础类型与数据结构
C++11中的基本类型和新引入的类型
C++11继续支持原始的C++类型,如整型、浮点型、字符型和指针等。此外,新增了:
std::vector
:动态大小的数组,高效插入、删除和查找元素。std::array
:大小固定但可初始化的数组,替代原始std::array
,提供现代接口。std::map
和std::unordered_map
:基于红黑树和哈希表的键值对容器,高效查找。std::list
和std::deque
:适用于不同场景的序列容器,std::deque
特别适合队列和多队列应用。
示例代码
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3};
for (int i : vec) {
std::cout << i << ' ';
}
std::cout << '\n';
std::array<int, 4> arr = {1, 2, 3, 4};
for (int i : arr) {
std::cout << i << ' ';
}
std::cout << '\n';
std::map<std::string, int> phonebook = {{"Alice", 1234}, {"Bob", 5678}};
for (const auto &entry : phonebook) {
std::cout << entry.first << ": " << entry.second << '\n';
}
std::list<int> lst = {1, 2, 3};
for (int i : lst) {
std::cout << i << ' ';
}
std::deque<int> dq = {1, 2, 3};
for (int i : dq) {
std::cout << i << ' ';
}
return 0;
}
控制流与函数式编程
断言和异常处理优化
异常处理在C++11中得到进一步优化,包含更强大try
、catch
和finally
块,允许更精细控制异常流。
示例代码
#include <iostream>
#include <stdexcept>
int safe_divide(int a, int b) {
if (b == 0) {
throw std::runtime_error("Division by zero!");
}
return a / b;
}
int main() {
try {
int result = safe_divide(10, 0);
} catch (const std::exception& e) {
std::cerr << "Caught an exception: " << e.what() << '\n';
}
return 0;
}
Lambda表达式的使用
std::function
和std::bind
简化了lambda表达式的使用。
示例代码
#include <iostream>
#include <functional>
#include <vector>
void print(const std::string &s) {
std::cout << s << '\n';
}
int main() {
std::vector<std::string> words = {"Hello", "World"};
std::for_each(words.begin(), words.end(), [](const std::string &word) {
print(word);
});
return 0;
}
并发编程与线程
示例代码
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx; // 创建互斥锁
void print_text(const std::string &text) {
std::lock_guard<std::mutex> lock(mtx);
std::cout << text << '\n';
}
int main() {
std::thread t1(print_text, "Thread 1");
std::thread t2(print_text, "Thread 2");
t1.join();
t2.join();
return 0;
}
std::async
和std::future
的使用
异步操作简化了并发编程。
示例代码
#include <iostream>
#include <future>
#include <string>
std::string long_task() {
std::this_thread::sleep_for(std::chrono::seconds(1));
return "Task completed!";
}
int main() {
std::future<std::string> result = std::async(std::launch::deferred, long_task);
std::cout << result.get() << '\n';
return 0;
}
模板与泛型编程
构造函数模板和常量模板
模板允许编写通用代码,针对不同类型的实例化。
示例代码
#include <iostream>
#include <string>
template <typename T>
void print(const T &value) {
std::cout << value << '\n';
}
int main() {
print(42); // 对整数实例化
print(std::string("Hello")); // 对字符串实例化
return 0;
}
元编程示例
#include <iostream>
#include <type_traits>
template <typename T>
struct integral_constant {
static const bool value = true;
};
template <typename T, typename U>
struct integral_constant<T, false> {
static const bool value = false;
};
int main() {
std::cout << std::boolalpha << integral_constant<int>::value << '\n';
std::cout << std::boolalpha << integral_constant<bool>::value << '\n';
return 0;
}
案例分析与实战
实战项目介绍
构建一个简单的事件处理库,利用std::vector
、std::function
和std::unique_ptr
等现代C++11特性。
示例代码
#include <iostream>
#include <vector>
#include <functional>
#include <memory>
class EventProcessor {
public:
void registerHandler(const std::function<void()> &handler) {
handlers.push_back(std::make_unique<std::function<void()>>(handler));
}
void trigger() {
for (auto &handler : handlers) {
handler();
}
}
private:
std::vector<std::unique_ptr<std::function<void()>>> handlers;
};
int main() {
EventProcessor processor;
processor.registerHandler([] { std::cout << "Event 1 triggered\n"; });
processor.registerHandler([] { std::cout << "Event 2 triggered\n"; });
processor.trigger();
return 0;
}
错误案例分析
-
陷阱1:未初始化的变量:
int x; // ... std::cout << x << '\n';
优化:确保变量初始化,避免未定义行为。
-
陷阱2:对容器进行循环中修改:
std::vector<int> vec = {1, 2, 3}; for (auto &i : vec) { if (i == 2) { vec.erase(std::remove(vec.begin(), vec.end(), i), vec.end()); } }
优化:使用范围基元简化循环,避免直接修改范围内的元素。
- 陷阱3:错误使用
boost
或Qt
的C++11支持:
优化:直接使用C++11特性,或选择兼容C++11的库版本。
结束语与后续学习资源推荐
通过深入理解C++11的特性,开发者可以构建更高效、安全且易于维护的现代C++应用程序。持续实践和学习,探索C++17、C++20等后续版本的特性,使代码更简练和强大。推荐使用在线学习平台慕课网等资源进一步学习现代C++编程技巧。
共同學(xué)習(xí),寫下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章