Creating an easy to maintain copy constructor

后端 未结 9 2619
夕颜
夕颜 2021-02-19 13:55

Consider the following class:

class A {

char *p;
int a, b, c, d;

public:
   A(const &A);
};

Note that I have to define a copy constructor

相关标签:
9条回答
  • 2021-02-19 14:31

    Replace char* with std::string.

    0 讨论(0)
  • 2021-02-19 14:31

    Unless your class has one function, which is managing a resource, you should never manage any resources directly. Always use a smart pointer or custom management class of some description. Typically, it's best to leave the implicit copy constructor, if you can. This approach also allows easy maintenance of the destructor and assignment operators.

    0 讨论(0)
  • 2021-02-19 14:35

    You really should use smart pointers here.

    This would avoid rewriting both the copy constructor and the affectation operator (operator=).

    Both of these are error prone.

    A common mistake with the operator= is implementing it that way:

    SomeClass& operator=(const SomeClass& b)
    {
      delete this->pointer;
      this->pointer = new char(*b.pointer); // What if &b == this or if new throws ?
    
      return *this;
    }
    

    Which fails when one does:

    SomeClass a;
    a = a; // This will crash :)
    

    Smart pointers already handle those cases and are obviously less error prone.

    Moreover, Smart pointers, like boost::shared_ptr can even handle a custom deallocation function (by default it uses delete). In practice, I rarely faced a situation where using a smart pointer instead of a raw pointer was unpractical.

    Just a quick note: boost smart pointer class, are header-only designed (based on templates) so they don't require additional dependencies. (Sometimes, it matters) You can just include them and everything should be fine.

    0 讨论(0)
提交回复
热议问题