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

recursive call in copy constructor

本文关键字:递归 调用 构造函数 复制      更新时间:2023-10-16

我按照三规则实现了一个类,结果我崩溃了。调试后,我得出的结论是复制构造函数反复调用自己而不是调用相等运算符。为什么会这样?它不应该调用相等运算符吗?

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

在复制构造函数中使用

*this = other; //(1)

哪个调用

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

由于other是按值传递的,因此需要创建副本。 然后调用1,它调用2然后调用1然后调用2和一轮,一轮,直到程序崩溃/终止。

您需要通过引用other,这样您实际上就不会像

tDataStruct& operator=(const tDataStruct& other) 

所有这些都说你是在倒退。 您应该使用复制和交换习惯用法,并使用复制构造函数实现您的operator =

复制构造函数调用赋值:

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