#include <iostream>
#include <string>
template<typename T>
class MyClass {
private:
T data;
public:
// 构造函数
MyClass(const T& value) : data(value) {
std::cout << "Constructor called." << std::endl;
}
// 析构函数
~MyClass() {
std::cout << "Destructor called." << std::endl;
}
// 拷贝构造函数
MyClass(const MyClass& other) : data(other.data) {
std::cout << "Copy constructor called." << std::endl;
}
// 移动构造函数,使用右值引用
MyClass(MyClass&& other) noexcept : data(std::move(other.data)) {
std::cout << "Move constructor called." << std::endl;
}
// 成员函数示例,使用右值引用优化移动语义
MyClass& operator=(MyClass&& other) noexcept {
if (this != &other) {
data = std::move(other.data);
}
std::cout << "Move assignment operator called." << std::endl;
return *this;
}
};
右值引用在这些函数中的优化作用说明:
- 移动构造函数:右值引用参数
MyClass&& other
允许我们识别临时对象(右值),并通过std::move
将资源从临时对象“窃取”过来,而不是进行深拷贝。这避免了不必要的数据复制,提高了性能。例如,如果T
是一个大的std::string
或复杂对象,移动构造函数可以直接转移其内部资源(如指针),而不是复制整个内容。
- 移动赋值运算符:类似地,右值引用参数
MyClass&& other
允许我们处理临时对象的赋值。通过std::move
,我们可以高效地将other
的资源转移到当前对象,避免不必要的复制操作,提升性能。