Creating an easy to maintain copy constructor

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

    You could separate your copyable members into a POD-struct and mantain your members requiring a managed copy separately.

    As your data members are private this can be invisible to clients of your class.

    E.g.

    class A {
    
    char *p;
    
    struct POData {
        int a, b, c, d;
        // other copyable members
    } data;
    
    public:
       A(const &A);
    };
    
    A(const A& a)
        : data( a.data )
    {
        p = DuplicateString( a.p );
        // other managed copies...
        // careful exception safe implementation, etc.
    }
    

提交回复
热议问题