我按照三规则实现了一个类,但我遇到了崩溃。经过调试,我得出的结论是,在复制构造函数第 51 行中,由于双端队列的某些内部逻辑,指针 oQueue 不为 NULL,因此构造函数尝试删除内存并失败。
然后我在某处读到我不应该在复制构造函数中检查 oQueue 的 NULLness,因为它可能没有在构造函数中初始化。由于默认构造函数,不应该始终将 oQueue 初始化为 NULL 吗?
#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=(const 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);
}