Creating an easy to maintain copy constructor

后端 未结 9 2662
夕颜
夕颜 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: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.

提交回复
热议问题