C++ 复制构造函数中的递归调用
我按照三的规则实现了一个类,结果我崩溃了。调试后,我得出结论,复制构造函数正在重复调用自身,而不是调用相等运算符。为什么会这样?它不应该调用相等运算符吗C++ 复制构造函数中的递归调用,c++,copy-constructor,copy-assignment,rule-of-three,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 nNumbe
#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);
}
#包括
#包括
#包括
#定义长度128
类型定义结构tDataStruct
{
字符序列[长度];
字符strB[长度];
信号的整数;
双*oQueue;
tDataStruct()
{
nNumberOfSignals=0;
//oQueue=NULL;
memset(strA,0,长度);
memset(strB,0,长度);
}
~tDataStruct()
{
if(NULL!=oQueue)
{
删除[]oQueue;
oQueue=NULL;
}
}
tDataStruct(const tDataStruct&other)//复制构造函数
{
如果(此!=&其他)
{
*这个=其他;
}
}
tDataStruct&operator=(tDataStruct-other)//复制分配
{
如果(此==&其他)
{
归还*这个;
}
strncpy_s(strA,other.strA,LENGTH);
strncpy_s(strB,other.strB,LENGTH);
nNumberOfSignals=other.nNumberOfSignals;
if(NULL!=oQueue)
{
删除[]oQueue;
oQueue=NULL;
}
如果(其他.nNumberOfSignals>0)
{
//memcpy(oQueue,other.oQueue,nNumberOfSignals);
}
归还*这个;
}
}tDataStruct;
int main()
{
tDataStruct-tData;
标准:德克先进先出;
先进先出后推(tData);
}
在您使用的复制构造函数中
*this = other; //(1)
哪个叫
tDataStruct& operator=(tDataStruct other) //(2)
由于other
是通过值传递的,因此需要进行复制。然后调用1
,调用2
,然后调用1
,然后调用2
,一轮又一轮,直到程序崩溃/终止
你需要参考other
,这样你就不会像这样复制了
tDataStruct& operator=(const tDataStruct& other)
所有这些都表明你是在倒行逆施。您应该使用并通过使用复制构造函数实现您的
运算符=
。您的复制构造函数调用赋值:
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
如果使用
std::array
而不是char[LENGTH]
和std::vector
而不是double*
,则编译器生成的所有成员都将正常工作。这不是标准方法。通常,赋值运算符在一个称为“复制和交换”(查找)的习惯用法中使用复制构造函数。这样做的结果是,您有一个严重的错误,导致UB(delete[]oQueue
可能会在未初始化的变量上被调用。因此,您随机删除了内存的某些部分(这不是一个好主意)。是的,我已经发现了该错误。谢谢