复制构造函数中的递归调用
recursive call in copy constructor
我按照三规则实现了一个类,结果我崩溃了。调试后,我得出的结论是复制构造函数反复调用自己而不是调用相等运算符。为什么会这样?它不应该调用相等运算符吗?
#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
相关文章:
- 返回递归调用和仅递归调用的区别
- 使用静态变量的递归调用的不同输出
- 复制构造函数中的递归调用
- 为什么编译器将其解析为函数指针而不是递归调用?
- 如何在 c++ 的类中递归调用函数方法?
- 了解使用堆栈实现队列的递归调用机制
- 如何通过函数指针递归调用类成员函数?
- 条件加倍时的递归调用
- 对可变参数函数的递归调用的链接器错误
- 将多个非原始递归调用转换为迭代解决方案
- 分段错误(核心转储)错误C++递归调用
- 无全局变量或功能参数的递归调用
- 在递归DP中,通过存储变量来分解递归调用:效率低下
- C - 为什么合并函数在递归调用后会逆转数组
- 递归调用中出现错误"[Error] expression list treated as compound expression in initializer [-fpermissive]"
- C / SFML:使用两个递归调用在屏幕上打印凸形形状仅显示第一个递归调用中的形状,而不是第二个
- C++中具有 100000 个递归调用的运行时错误
- 递归调用可变参数模板函数重载时的不明确调用
- 如何在 c++ 中递归调用类
- 带有两个递归调用的递归算法的时间复杂性