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

标签 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);
}

最佳答案

在你使用的复制构造函数中

*this = other; //(1)

调用

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

因为 other 是按需要复制的值传递的。然后调用 1,后者调用 2,然后调用 1,然后调用 2,一轮又一轮直到程序崩溃/终止为止。

您需要通过引用获取other,这样您实际上就不会复制

tDataStruct& operator=(const tDataStruct& other) 

所有这些都说你在倒退。你应该使用 copy and swap idiom并使用您的复制构造函数实现您的 operator =

关于c++ - 复制构造函数中的递归调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52741605/

相关文章:

c++ - 仅定义重要的复制操作

C++ 如何在数组中存储对象而不删除它们

c++ - LInux/c++,如何同时保护两个数据结构?

c++ - 如何将 3D 点云转换为深度图像?

c++ - 使用 const 限定符获取对象私有(private)属性的问题

c++ - 没有按预期调用复制构造函数

c++ - 从指针或指针链(对象指针、模板)复制数据

c++ - 不调用复制赋值运算符=

c++ - Uncrustify 对齐尾随注释?

c++ - windows c++14 上的 clang-cl 状态