复制构造函数中的递归调用

时间:2018-10-10 13:40:29

标签: c++ copy-constructor copy-assignment rule-of-three

我遵循三个规则实现了一个类,但发生崩溃。通过调试,我得出的结论是,复制构造函数正在反复调用自身,而不是调用相等运算符。为什么会这样呢?它不应该调用相等运算符吗?

#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);
}

2 个答案:

答案 0 :(得分:7)

在复制构造函数中使用

*this = other; //(1)

调用

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

由于other按值传递,因此需要进行复制。然后调用1,然后调用2,然后调用1,然后调用2,然后再进行一轮,直到程序崩溃/终止。 / p>

您需要引用other作为参考,这样您才不会真正复制

tDataStruct& operator=(const tDataStruct& other) 

所有这些都表示您正在反向进行此操作。您应该使用copy and swap idiom并通过复制构造函数实现operator =

答案 1 :(得分:0)

您的副本构造函数调用分配:

tDataStruct(const tDataStruct& other) // copy constructor
{
    // NOTE: this redundant check is always true. 
    // Please remove the if.
    if (this != &other) 
    {
        *this = other;
    }
 }

然后,由于赋值运算符通过值(而不是引用)获取对象,因此调用复制构造函数以复制参数:

tDataStruct& operator=(tDataStruct other) // copy assignment
{

这就是您相互递归的方式。

尝试通过引用传递:

tDataStruct& operator=(const tDataStruct &other) // copy assignment