#include <iostream>
#include <utility>
#include <vector>
class MyClass {
public:
MyClass() {
std::cout << "Constructor called" << std::endl;
}
MyClass(const MyClass& other) {
std::cout << "Copy constructor called" << std::endl;
}
MyClass(MyClass&& other) noexcept {
std::cout << "Move constructor called" << std::endl;
}
~MyClass() {
std::cout << "Destructor called" << std::endl;
}
};
void exampleFunction() {
std::vector<MyClass> vec;
// 使用 push_back 添加一个临时对象,触发移动构造函数
vec.push_back(MyClass()); // 输出: Constructor called, Move constructor called
// 如果不使用 std::move,添加一个命名对象会触发拷贝构造函数
MyClass obj;
vec.push_back(obj); // 输出: Copy constructor called
// 使用 std::move 强制移动语义
MyClass obj2;
vec.push_back(std::move(obj2)); // 输出: Move constructor called
}
int main() {
exampleFunction();
return 0;
}
MyClass
类定义了构造函数、拷贝构造函数、移动构造函数和析构函数,并在每个函数中输出相应的信息以便观察调用情况。std::vector<MyClass>
对象 vec
。push_back
添加一个临时对象,触发移动构造函数(因为编译器可以自动推断出这是一个右值)。obj
,触发拷贝构造函数(因为 obj
是左值)。std::move
将命名对象 obj2
转换为右值,从而触发移动构造函数。exampleFunction
来演示上述行为。通过这个示例代码,可以看到 std::move
的作用是将左值转换为右值,从而允许使用移动语义,提高性能并减少不必要的拷贝操作。
上一篇:c++ 右值引用
下一篇:c++重载运算符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站