In C++, 'use of deleted function' errors typically occur when trying to use functions that have been explicitly deleted by the programmer. This often involves copy constructors, copy assignment operators, move constructors, or move assignment operators. Understanding why these functions have been deleted is crucial for resolving these errors.
Here are steps to resolve these errors:
std::shared_ptr
or std::unique_ptr
) to manage them.
#include
#include
class NonCopyable {
public:
NonCopyable() = default;
// Deleting copy constructor and copy assignment operator
NonCopyable(const NonCopyable&) = delete;
NonCopyable& operator=(const NonCopyable&) = delete;
// Move constructor and move assignment operator
NonCopyable(NonCopyable&&) = default;
NonCopyable& operator=(NonCopyable&&) = default;
void show() {
std::cout << "NonCopyable instance" << std::endl;
}
};
int main() {
NonCopyable obj1;
// NonCopyable obj2 = obj1; // This line would cause a 'use of deleted function' error
NonCopyable obj2 = std::move(obj1); // Correct usage with move semantics
obj2.show();
return 0;
}
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?