#include <iostream>
#include <vector>
class MyClass {
public:
int* data;
std::size_t size;
// Constructor
MyClass(std::size_t s) : size(s) {
data = new int[s];
std::cout << "Constructed with size: " << size << std::endl;
}
// Destructor
~MyClass() {
delete[] data;
std::cout << "Destroyed" << std::endl;
}
// Copy Constructor
MyClass(const MyClass& other) : size(other.size) {
data = new int[size];
std::copy(other.data, other.data + size, data);
std::cout << "Copy Constructed" << std::endl;
}
// Move Constructor
MyClass(MyClass&& other) noexcept : data(nullptr), size(0) {
data = other.data;
size = other.size;
other.data = nullptr;
other.size = 0;
std::cout << "Move Constructed" << std::endl;
}
// Copy Assignment Operator
MyClass& operator=(const MyClass& other) {
if (this == &other)
return *this;
delete[] data;
size = other.size;
data = new int[size];
std::copy(other.data, other.data + size, data);
std::cout << "Copy Assigned" << std::endl;
return *this;
}
// Move Assignment Operator
MyClass& operator=(MyClass&& other) noexcept {
if (this == &other)
return *this;
delete[] data;
data = other.data;
size = other.size;
other.data = nullptr;
other.size = 0;
std::cout << "Move Assigned" << std::endl;
return *this;
}
};
int main() {
std::vector<MyClass> vec;
vec.reserve(2);
MyClass obj1(10);
vec.push_back(std::move(obj1)); // Uses move constructor
MyClass obj2(20);
vec.push_back(std::move(obj2)); // Uses move constructor
return 0;
}