In C++, a copy constructor is a special constructor used to create a new object as a copy of an existing object. Writing a safe copy constructor is essential to avoid issues such as double deletions, memory leaks, and data corruption. A well-designed copy constructor implements the Rule of Three (or the Rule of Five in C++11), ensuring that memory management is properly handled. Here are the key aspects of writing a safe copy constructor:
class MyClass {
private:
int* data; // Pointer to an int array
size_t size; // Size of the array
public:
// Constructor
MyClass(size_t s) : size(s) {
data = new int[size];
}
// Copy Constructor
MyClass(const MyClass& other) {
// Allocate new memory
size = other.size;
data = new int[size];
// Copy the data
for (size_t i = 0; i < size; i++) {
data[i] = other.data[i];
}
}
// Destructor
~MyClass() {
delete[] data;
}
// Assignment operator
MyClass& operator=(const MyClass& other) {
if (this == &other) return *this; // self-assignment guard
delete[] data; // Free existing resource
size = other.size;
data = new int[size]; // Allocate new memory
for (size_t i = 0; i < size; i++) {
data[i] = other.data[i]; // Copy the data
}
return *this;
}
};
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?