【问题标题】:deque push back default constructor not called未调用双端队列推回默认构造函数
【发布时间】: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实现了。现在,您的赋值运算符有很多漏洞。像没有赋值运算符一样只编写复制构造函数要容易得多,然后使用已经提到的复制/交换技术返回并实现赋值运算符。
  • 我已经完成了一切工作,我只是问了这个问题,以增加我对事情应该如何的了解并改进我的概念。

标签: c++ stl stddeque


【解决方案1】:

复制构造函数的实现调用了未定义的行为,因为正在构造的对象的成员变量尚未初始化。

您可以使用默认构造函数先初始化成员变量以获得可预测的行为。

tDataStruct(const tDataStruct& other) : tDataStruct()
{
   *this = other;
}

【讨论】:

    猜你喜欢
    • 2015-10-09
    • 2016-10-14
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 2012-10-17
    相关资源
    最近更新 更多