Creating an easy to maintain copy constructor

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

    So the default copy constructor is called first and then the deep copy is performed. Unfortunately this doesn't seem to work.

    Is there any better way to do this? One restriction - I can't use shared/smart pointers.

    If I understand correctly, your question, you could consider using an initialization function:

    class A
    {
        int i, j;
        char* p;
    
        void Copy(int ii, int jj, char* pp); // assign the values to memebers of A
    public:
        A(int i, int j, char* p);
        A(const A& a);
    };
    
    A::A(int i, int j, char* p)
    {
        Copy(i, j, p);
    }
    
    A::A(const A& a)
    {
        Copy(a.i, a.j, a.p);
    }
    

    That said, you really should consider using RAII ( there's a reason people keep recommending it :) ) for your extra resources.

    If I can't use RAII, I still prefer creating the copy constructor and using initializer lists, for every member (actually, I prefer doing so even when using RAII):

    A::A(int ii, int lj, char* pp)
        : i(ii)
        , j(jj)
        , p( function_that_creates_deep_copy(pp) )
    {
    }
    
    A::A(const A& a)
        : i(a.i)
        , j(a.j)
        , p( function_that_creates_deep_copy(a.p) )
    {
    }
    

    This has the advantage of "explicitness" and is easy to debug (you can step in and see what it does for each initialization).

提交回复
热议问题