How do I explain copy vs move semantics with examples?

Copy semantics refers to the process where a new copy of an object is created when passing it around or assigning it, which often leads to performance overhead and potential inefficiency, especially with large objects. In contrast, move semantics allows the resources of an object to be transferred or "moved" to another object, enabling optimizations and reducing overhead.

Copy Semantics Example

class Resource { public: Resource() { std::cout << "Resource acquired." << std::endl; } ~Resource() { std::cout << "Resource destroyed." << std::endl; } Resource(const Resource& other) { std::cout << "Resource copied." << std::endl; } Resource& operator=(const Resource& other) { std::cout << "Resource assigned." << std::endl; return *this; } }; void copyExample() { Resource res1; // Resource acquired. Resource res2 = res1; // Resource copied. }

Move Semantics Example

class Resource { public: Resource() { std::cout << "Resource acquired." << std::endl; } ~Resource() { std::cout << "Resource destroyed." << std::endl; } Resource(Resource&& other) noexcept { std::cout << "Resource moved." << std::endl; } Resource& operator=(Resource&& other) noexcept { std::cout << "Resource move assigned." << std::endl; return *this; } }; void moveExample() { Resource res1; // Resource acquired. Resource res2 = std::move(res1); // Resource moved. }

copy semantics move semantics C++ resource management performance optimization