KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
In c++ when classes contains dynamically allocated data it is usually reasonable to explicitly define copy constructor, operator= and destructor. But the activity of these special methods overlaps. More specifically operator= usually first does some destruction and then it does coping similar to the one in copy constructor. My question is how to write this the best way without repeating the same lines of code and without the need for processor to do unnecessary work (like unnecessary copying). I usually end up with two helping methods. One for construction and one for destruction. The first is called from both copy constructor and operator=. The second is used by destructor and operator=. Here is the example code: template <class T> class MyClass { private: // Data members int count; T* data; // Some of them are dynamicly allocated void construct(const MyClass& myClass) { // Code which does deep copy this->count = myClass.count; data = new T[count]; try { for (int i = 0; i < count; i++) data[i] = myClass.data[i]; } catch (...) { delete[] data; throw; } } void destruct() { // Dealocate all dynamicly allocated data members delete[] data; } public: MyClass(int count) : count(count) { data = new T[count]; } MyClass(const MyClass& myClass) { construct(myClass); } MyClass& operator = (const MyClass& myClass) { if (this != &myClass) { destruct(); construct(myClass); } return *this; } ~MyClass() { destruct();
Tags (comma-separated)
Save Edits
Cancel