¿Qué es la semántica de movimiento (move semantics) en C++11 y cómo funciona?
¡Hola a todos! Empecé a estudiar C++11 y constantemente me topo con el término "move semantics", pero no logro entender completamente qué es y para qué sirve. Leí varios artículos, pero en todos los ejemplos son algo abstractos.
Tengo este código. Supongamos que escribo una clase que gestiona un array dinámico:
```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));
s