【发布时间】:2018-10-11 05:58:33
【问题描述】:
我按照三规则实现了一个类,但我遇到了崩溃。经过调试,我得出的结论是,在复制构造函数第 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);
}
【问题讨论】:
-
您是否希望在复制构造函数之前调用默认构造函数?事实并非如此。
-
NULL现在是个坏习惯,更喜欢nullptr。 -
与
delete对应的new在哪里? -
编写复制构造函数的常用方法是完全实现它,根本不调用赋值运算符。那么赋值运算符就很容易被copy / swap实现了。现在,您的赋值运算符有很多漏洞。像没有赋值运算符一样只编写复制构造函数要容易得多,然后使用已经提到的复制/交换技术返回并实现赋值运算符。
-
我已经完成了一切工作,我只是问了这个问题,以增加我对事情应该如何的了解并改进我的概念。