概述
C++11引入了一系列改进和新特性,旨在提升语言的性能、易用性和安全性。这些新特性包括模板元编程的增强、自动类型推断、范围基于的for循环、可变参数模板、并行编程支持等。本文将详细介绍C++11中的可变参数模板、通用迭代器、constexpr函数等新特性,并以示例代码指导如何在实践案例中应用这些特性。
C++11特性介绍与实践
可变参数模板示例
#include <iostream>
template <typename... Args>
void log(const char* format, Args... args) {
std::cout << std::vsnprintf(nullptr, 0, format, std::make_tuple(args...)) << std::endl;
}
int main() {
log("Hello, World!");
log("The sum of %d and %d is %d", 1, 2, 3);
return 0;
}
使用std::optional
处理空值
#include <optional>
void process() {
auto result = std::optional<std::string>{"Hello"};
if (result) {
std::cout << *result << std::endl;
} else {
std::cout << "No result" << std::endl;
}
}
使用std::move
优化函数调用
#include <functional>
void exchange(int& a, int& b) {
std::swap(a, b);
}
int main() {
int x = 5, y = 10;
exchange(x, y); // 使用std::move提高性能
std::cout << "x = " << x << ", y = " << y << std::endl;
return 0;
}
使用范围for循环遍历容器
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
使用constexpr
进行计算
#include <iostream>
constexpr int add(int a, int b) {
return a + b;
}
int main() {
std::cout << "The sum is: " << add(10, 20) << std::endl;
return 0;
}
使用std::optional
和std::array
#include <optional>
#include <array>
int main() {
std::array<int, 3> data = {1, 2, 3};
std::optional<std::array<int, 3>> optData = data;
if (optData) {
for (int val : *optData) {
std::cout << val << " ";
}
}
return 0;
}
使用std::find_if
和std::reverse
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {3, 2, 1, 4, 5};
auto it = std::find_if(numbers.begin(), numbers.end(), [](int n) { return n > 2; });
if (it != numbers.end()) {
std::cout << *it << " is the first number greater than 2." << std::endl;
} else {
std::cout << "No number greater than 2 found." << std::endl;
}
std::reverse(numbers.begin(), numbers.end());
for (int n : numbers) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
并发与线程支持的示例
使用std::atomic
和std::mutex
#include <iostream>
#include <thread>
#include <atomic>
#include <mutex>
std::atomic<int> counter(0);
std::mutex mtx;
void incrementCounter() {
std::lock_guard<std::mutex> lock(mtx);
++counter;
std::cout << "Counter incremented to " << counter << std::endl;
}
int main() {
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
t1.join();
t2.join();
return 0;
}
使用std::async
进行并发计算
#include <iostream>
#include <future>
std::future<int> asyncCompute() {
std::promise<int> promise;
std::future<int> future = promise.get_future();
std::thread t([]() {
int result = 100;
promise.set_value(result);
});
t.join();
return future;
}
int main() {
int result = asyncCompute().get();
std::cout << "Result: " << result << std::endl;
return 0;
}
实践案例与代码示例
使用std::make_unique
进行内存管理
#include <iostream>
#include <memory>
struct MyClass {
MyClass() { std::cout << "Created" << std::endl; }
~MyClass() { std::cout << "Destroyed" << std::endl; }
};
int main() {
std::unique_ptr<MyClass> ptr = std::make_unique<MyClass>();
ptr->MyClass::MyClass(); // Created
// 使用完毕后自动调用析构函数
return 0;
}
具体并发场景下的线程池应用
#include <iostream>
#include <thread>
#include <vector>
#include <future>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
int counter = 0;
void incrementCounter(int n) {
std::unique_lock<std::mutex> lock(mtx);
for (int i = 0; i < n; ++i) {
++counter;
}
cv.notify_one();
}
int main() {
std::vector<std::future<void>> futures;
const int nThreads = 10;
const int nIncrement = 10000000;
for (int i = 0; i < nThreads; ++i) {
futures.push_back(std::async(std::launch::async, incrementCounter, nIncrement));
}
for (auto& future : futures) {
future.wait();
}
std::cout << "Final counter value: " << counter << std::endl;
return 0;
}
本文通过全面介绍了C++11的关键特性及其在实际编程中的应用方法,为学习者提供了从基础到实践的快速入门指南。C++11的引入为C++语言带来了许多重要的改进,使得编写更安全、更高效和更易于维护的代码成为可能。
點擊查看更多內容
為 TA 點贊
評論
評論
共同學習,寫下你的評論
評論加載中...
作者其他優(yōu)質文章
正在加載中
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦