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

Dan*_*sin 0 c++ copy-constructor rule-of-three copy-assignment

我按照三个规则实施了一个类,我遇到了崩溃.在调试时,我得出结论,复制构造函数反复调用自身而不是调用相等运算符.为什么会这样?它不应该调用相等运算符吗?

#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);
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 7

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

*this = other; //(1)
Run Code Online (Sandbox Code Playgroud)

哪个叫

tDataStruct& operator=(tDataStruct other)  //(2)
Run Code Online (Sandbox Code Playgroud)

other按值传递,它需要进行复印.然后调用1,然后调用哪个调用2然后调用1然后调用2圆形和圆形直到程序崩溃/终止.

你需要other通过引用,所以你实际上不需要复制

tDataStruct& operator=(const tDataStruct& other) 
Run Code Online (Sandbox Code Playgroud)

所有这一切都说你正在倒退.您应该使用复制和交换习惯用法operator =使用您的复制构造函数来实现.