什么是C++11中的移动语义(move semantics)以及它是如何工作的?
大家好!我开始学习C++11,经常遇到"move semantics"这个术语,但始终无法完全理解它是什么以及为什么需要它。我读过不同的文章,但到处都是抽象的示例。
我有这样的代码。假设我写了一个管理动态数组的类:
```cpp
#include
#include
class MyArray {
public:
int* data;
size_t size;
MyArray(size_t s) : size(s) {
data = new int[size];
std::cout << "Constructor called\n";
}
MyArray(const MyArray& other) : size(other.size) {
data = new int[size];
std::memcpy(data, other.data, size * sizeof(int));
std::cout << "Copy constructor called\n";
}
MyArray& operator=(const MyArray& other) {
if (this != &other) {
delete[] data;
size = other.size;
data = new int[size];
std::memcpy(data, other.data, size * sizeof(int));
std::cout << "Copy assignment cal"
```