Copy Constructor Using Assinmgent Operator?

I'm not a newbie, but this sound's like a newbie question.

Copy constructors and assignment operators can have a lot of code in common.

When written for classes that contain a large number of variables, duplicating everything could be difficult.

Is it safe to use a an assignment operator in a copy constructor? This would allow a single function to do the heavy lifting.

One issue would be the handling of a pointer which would have to be initialized to NULL in the copy constructor before the assignment operator is called.

It's imperative to set those pointers to NULL in the copy constructor.

Is this effective and safe?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
    TEST_CLASS(
            const TEST_CLASS& record) // Copy constructor
    {
        if(this != NULL)
        {
            if(&record == NULL)
            {
                memset(this, 0x00, sizeof (TEST_CLASS));
            }
            else
            {
                test_ptr = NULL;
                *this = record;
            }
        }
    }

    TEST_CLASS& operator=(
            const TEST_CLASS& record) // Assignment operator
    {
        if (this != NULL)
        {
            if(&record == NULL)
            {
                memset(this, 0x00, sizeof (TEST_CLASS));
            }
            else
            {
                application_id = record.application_id;
 
                if(record.test_ptr == NULL)
                {
                    if(test_ptr != NULL)
                    {
                        delete test_ptr;
                        test_ptr = NULL;
                    }
                }
                else
                {
                    test_ptr = new TEST_CLASS_2(*record.test_ptr);

                    *test_ptr = *record.test_ptr;
                }
           }
        }

        return *this;
    }


Thanks
Larry
I believe this is legal, though I would prefer implementing it the other way around using the copy-and-swap idiom, as the copy constructor can benefit from, for example, direct construction of its members via the initializer list.

Something else about your code however:

On line 6, you try to check if the address of record is NULL, which makes no sense. You cannot have a null reference by definition; if you actually have an object anyway it's address could not possibly be null. Ditto for line 23.

On line 21, you check if this is NULL, which is not necessary as calling a method on a null pointer is undefined behavior anyway.
Frankly, that code looks utterly unmaintainable.

Please show the definition of the class and explain the purpose of the pointer members.
Topic archived. No new replies allowed.