右值拷贝构造示例
时间: 2023-07-07 16:18:06 浏览: 46
以下是一个简单的右值拷贝构造函数的示例:
```c++
#include <iostream>
#include <cstring>
class MyString {
public:
MyString() : str(nullptr), len(0) {}
MyString(const char* s) : str(new char[strlen(s) + 1]), len(strlen(s)) {
strcpy(str, s);
}
MyString(const MyString& other) : str(new char[other.len + 1]), len(other.len) {
strcpy(str, other.str);
}
MyString(MyString&& other) : str(other.str), len(other.len) {
other.str = nullptr;
other.len = 0;
}
~MyString() {
delete[] str;
}
private:
char* str;
int len;
};
int main() {
MyString s1("Hello, world!"); // 普通构造函数
MyString s2(s1); // 拷贝构造函数
MyString s3(std::move(s1)); // 右值拷贝构造函数
return 0;
}
```
在上面的示例中,MyString类有三个构造函数:普通构造函数、拷贝构造函数和右值拷贝构造函数。在main函数中,我们分别使用这三种构造函数创建了三个MyString对象s1、s2和s3。
其中,s1使用普通构造函数创建,s2使用拷贝构造函数创建,s3使用右值拷贝构造函数创建。右值拷贝构造函数中,我们将other.str和other.len的值移动到新对象中,并将other.str和other.len置为nullptr和0,避免了资源重复释放。