② 使用std::vector实现移动语义
std::vector是C++中常用的动态数组容器,可以存储任意类型的数据,具有高度的可扩展性和灵活性。在实现移动语义时,我们可以使用std::vector来避免不必要的对象拷贝和移动。下面是一个使用std::vector实现移动语义的例子:
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass(int size) : size_(size) {
data_ = new int[size_];
for (int i = 0; i < size_; i++) {
data_[i] = i;
}
std::cout << "Constructor called." << std::endl;
}
MyClass(const MyClass& other) : size_(other.size_) {
data_ = new int[size_];
for (int i = 0; i < size_; i++) {
data_[i] = other.data_[i];
}
std::cout << "Copy constructor called." << std::endl;
}
MyClass(MyClass&& other) noexcept : size_(other.size_), data_(other.data_) {
other.size_ = 0;
other.data_ = nullptr;
std::cout << "Move constructor called." << std::endl;
}
~MyClass() {
delete[] data_;
std::cout << "Destructor called." << std::endl;
}
MyClass& operator=(const MyClass& other) {
if (this != &other) {
delete[] data_;
size_ = other.size_;
data_ = new int[size_];
for (int i = 0; i < size_; i++) {
data_[i] = other.data_[i];
}
}
std::cout << "Copy assignment operator called." << std::endl;
return *this;
}
MyClass& operator=(MyClass&& other) noexcept {
if (this != &other) {
delete[] data_;
size_ = other.size_;
data_ = other.data_;
other.size_ = 0;
other.data_ = nullptr;
}
std::cout << "Move assignment operator called." << std::endl;
return *this;
}
private:
int size_;
int* data_;
};
int main() {
auto ptr1 = std::make_unique<MyClass>(10);
auto ptr2 = std::move(ptr1);
return 0;
}
在上面的例子中,我们使用std::make_unique创建了一个std::unique_ptr对象ptr1,并将其移动到ptr2中。这样可以避免不必要的对象拷贝和移动,提高程序的性能和可维护性。