// C++ 右值引用示例代码
#include <iostream>
#include <utility> // for std::move
class MyClass {
public:
int data;
// 默认构造函数
MyClass(int value) : data(value) {
std::cout << "Constructor called for: " << data << std::endl;
}
// 移动构造函数
MyClass(MyClass&& other) noexcept : data(other.data) {
std::cout << "Move constructor called for: " << data << std::endl;
other.data = 0; // 将源对象置为有效但未指定的状态
}
// 拷贝构造函数
MyClass(const MyClass& other) : data(other.data) {
std::cout << "Copy constructor called for: " << data << std::endl;
}
// 析构函数
~MyClass() {
std::cout << "Destructor called for: " << data << std::endl;
}
};
void exampleFunction(MyClass obj) {
std::cout << "Inside function, obj.data is: " << obj.data << std::endl;
}
int main() {
// 创建一个临时对象并传递给函数,触发移动语义
exampleFunction(MyClass(42)); // 这里会调用移动构造函数
// 创建一个命名对象并传递给函数,触发拷贝语义
MyClass namedObject(100);
exampleFunction(namedObject); // 这里会调用拷贝构造函数
return 0;
}
MyClass&& other
) 是 C++11 引入的一种新特性,用于区分左值和右值。右值引用只能绑定到临时对象(即右值),而左值引用可以绑定到任何对象。std::move
是一个工具函数,它将一个左值转换为右值引用,从而允许使用移动语义。在这个例子中,我们展示了如何定义和使用移动构造函数,并解释了右值引用的作用。
上一篇:c++向下取整
下一篇:c++ std::move
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站