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.
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.
}
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.
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?