使用复制构造函数后,双重释放子对象 [英] Double free of child object after using the copy constructor

查看:73
本文介绍了使用复制构造函数后,双重释放子对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚为什么(似乎)一个对象被破坏了两次。

I am having trouble figuring out why (it seems like) an object is being destructed twice.

如果我创建一个包含以下内容的类(B)的对象,一个另一个类的对象(A),我复制了这个对象。复制的对象被破坏两次。虽然看起来像这样。我无法确定输出结果。

If i create a object of a class (B) which contains an object of another class (A) and i copy this object. the copied object is destructed twice. Altough it looks like this. I am unable to figure out this output.

我创建了以下(最低要求)示例,似乎触发了我的问题:

I have created the following (minimum?) example which seems to trigger my issue:

#include <stdio.h>
#include <stdint.h>

template <class T>
class A
{
public:
    A()
    {
        myCtr = ++ctr;
        printf("class A default Constructor - object id: %u\n", myCtr);
    }

    A(const A<T> &a2) {
        myCtr = ++ctr;
        printf("class A copy constructor - object id: %u\n", myCtr);

    }

    ~A()
    {
        printf("class A destructor - object id: %u\n", myCtr);
    }

    void add(T item) {
        /* Irrelevant */
    }

private:
    uint64_t myCtr;
    static uint64_t ctr;
};

class B
{
public:
    B() {

    }

    B(char * input, uint32_t len) {
        for (uint32_t i = 0; i < len; i++)
        {
            characters.add(input[i]);
        }
    }

    B(const B &b2) {
        characters = A<char>(b2.characters);
    }

    ~B() {

    }


private:
    A<char> characters;
};

template <class T>
uint64_t A<T>::ctr = 0;

int main(int argc, char *argv[]) {
    B b1 = B((char *)"b1", 2);
    B b2 = B(b1);

    return 0;
}

这将产生以下输出:

class A default Constructor - object id: 1
class A default Constructor - object id: 2
class A copy constructor - object id: 3
class A destructor - object id: 3
class A destructor - object id: 3
class A destructor - object id: 1

对象id 3被破坏了两次,而对象id 2却没有被破坏。

object id 3 is destructed twice while object id 2 is not destructed at all.

我正在使用以下命令编译器:
Microsoft(R)C / C ++优化编译器版本19.14.26429.4

I am using the following compiler: Microsoft (R) C/C++ Optimizing Compiler Version 19.14.26429.4

以防万一您投反对票。请说明原因。我会很乐意尝试改善我的问题。

In case you down vote. Please specify why. I will gladly try to improve my question.

推荐答案

您需要遵循第5条规则。如果您实现了一个非平凡的析构函数,请复制/移动分配/构造,则必须实现全部5个,或者给出一个很好的理由而不这么做,或者删除它们。

You need to follow the rule of 5. If you implement a non-trivial destructor, copy/move assign/construct, you must implement all 5, or give a good reason why not, or delete them.

您实施销毁和复制ctor。您忽略了其他3个。

You implemented destory and copy ctor. You neglected the other 3. Add them.

还有什么个字符= A< char>(b2.characters); 您的复印控制器将调用复印任务。您没有追踪的原因,这就是您的计数不正确的原因。您可以在柜台上分配。

What more characters = A<char>(b2.characters); your copy ctor calls a copy assignment. Which you don't track, which is why your count is off. You assign over the counter.

这篇关于使用复制构造函数后,双重释放子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆