欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

C++ 移动语义与完美转发:性能优化关键

时间:2026年08月12日 05:42:24 浏览:1

C++ 移动语义与完美转发:性能优化关键


移动语义允许资源转移而非拷贝,避免不必要的开销。


1. 右值引用与移动构造函数


class MyString {
char* data;
public:
// 移动构造
MyString(MyString&& other) noexcept : data(other.data) {
other.data = nullptr;
}
// 移动赋值
MyString& operator=(MyString&& other) noexcept {
if (this != &other) {
delete[] data;
data = other.data;
other.data = nullptr;
}
return *this;
}
};

2. std::move 与 std::forward



  • std::move:无条件转换为右值,启用移动。

  • std::forward:保留实参的左右值属性(完美转发)。


std::vector<int> v1 = {1,2,3};
auto v2 = std::move(v1); // 移动,v1 变为空

template<typename T>
void wrapper(T&& arg) {
// 按原始类型转发
func(std::forward<T>(arg));
}

3. 移动语义与 STL 容器


STL 容器大量使用移动,如 push_back(T&&)emplace_back 直接构造。


4. noexcept 对性能的影响


移动构造函数标记 noexcept 可使容器在扩容时使用移动而非拷贝,显著提升性能。


移动语义是现代 C++ 高性能编程的核心。