Search code examples
c++copy-constructorcopy-assignmentrule-of-three

recursive call in copy constructor


I implemented a class following the rule of three, and I am getting a crash. Upon debugging I have came to the conclusion that the copy constructor is calling itself repeatedly instead of calling the equality operator. Why is this so? Shouldn't it call the equality operator?

#include <iostream>
#include <deque>
#include <cstdlib>
#define LENGTH 128

typedef struct tDataStruct
{

char strA[LENGTH];

char strB[LENGTH];
int nNumberOfSignals;
double* oQueue;

tDataStruct()
{
    nNumberOfSignals = 0;
    //oQueue = NULL;
    memset(strA, 0, LENGTH);
    memset(strB, 0, LENGTH);
}

~tDataStruct()
{
    if (NULL != oQueue)
    {
        delete[] oQueue;
        oQueue = NULL;
    }
}

tDataStruct(const tDataStruct& other) // copy constructor
{
    if (this != &other)
    {
        *this = other;
    }

}
tDataStruct& operator=(tDataStruct other) // copy assignment
{
    if (this == &other)
    {
        return *this;
    }
    strncpy_s(strA, other.strA, LENGTH);
    strncpy_s(strB, other.strB, LENGTH);
    nNumberOfSignals = other.nNumberOfSignals;
    if (NULL != oQueue)
    {
        delete[] oQueue;
        oQueue = NULL;
    }
    if (other.nNumberOfSignals > 0)
    {
        //memcpy(oQueue, other.oQueue, nNumberOfSignals);
    }
    return *this;
}
} tDataStruct;


int main()
{
    tDataStruct tData;

    std::deque<tDataStruct> fifo;

    fifo.push_back(tData);
}

Solution

  • In your copy constructor you use

    *this = other; //(1)
    

    which calls

    tDataStruct& operator=(tDataStruct other)  //(2)
    

    as other is passed by value it needs to make a copy. That then calls 1, which call 2 which then calls 1 which then calls 2 and a round and a round you'll go until the program crashes/terminates.

    You need to take other by reference so you don't actually make a copy like

    tDataStruct& operator=(const tDataStruct& other) 
    

    All that said you are doing this backwards. You should use the copy and swap idiom and implement your operator = by using your copy constructor.