// C++ 右值引用示例代码
#include <iostream>
#include <utility> // for std::move
class MyClass {
public:
int data;
// 普通构造函数
MyClass(int value) : data(value) {
std::cout << "普通构造函数调用, data = " << data << std::endl;
}
// 移动构造函数
MyClass(MyClass&& other) noexcept : data(other.data) {
std::cout << "移动构造函数调用, data = " << data << std::endl;
other.data = 0; // 将原对象置为有效但未指定的状态
}
// 复制构造函数
MyClass(const MyClass& other) : data(other.data) {
std::cout << "复制构造函数调用, data = " << data << std::endl;
}
// 移动赋值运算符
MyClass& operator=(MyClass&& other) noexcept {
if (this != &other) {
data = other.data;
other.data = 0; // 将原对象置为有效但未指定的状态
std::cout << "移动赋值运算符调用, data = " << data << std::endl;
}
return *this;
}
// 复制赋值运算符
MyClass& operator=(const MyClass& other) {
if (this != &other) {
data = other.data;
std::cout << "复制赋值运算符调用, data = " << data << std::endl;
}
return *this;
}
~MyClass() {
std::cout << "析构函数调用, data = " << data << std::endl;
}
};
void testRValueReference() {
// 创建一个临时对象并使用右值引用传递给函数
MyClass obj1(10);
MyClass obj2(std::move(obj1)); // 调用移动构造函数
// 使用右值引用进行赋值操作
MyClass obj3(20);
MyClass obj4(30);
obj4 = std::move(obj3); // 调用移动赋值运算符
}
int main() {
testRValueReference();
return 0;
}
右值引用(T&&
)是C++11引入的一个特性,用于区分左值和右值。右值引用可以绑定到临时对象(即右值),而左值引用(T&
)只能绑定到已命名的对象(即左值)。
移动语义:通过右值引用来实现移动语义,可以避免不必要的复制操作,提高性能。移动构造函数和移动赋值运算符允许将资源从一个对象“移动”到另一个对象,而不是复制它们。
std::move:std::move
是一个辅助函数,它将左值转换为右值引用,从而允许调用移动构造函数或移动赋值运算符。
noexcept:在移动构造函数和移动赋值运算符中使用 noexcept
表示这些操作不会抛出异常,这有助于优化编译器的处理逻辑。
测试函数:testRValueReference
函数展示了如何使用右值引用来创建对象以及进行赋值操作。
上一篇:c++ getline函数用法
下一篇:c++获取数组长度
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站