明确的析构函数调用不起作用 [英] Explicit destructor call is not working

查看:172
本文介绍了明确的析构函数调用不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的c ++类的简化版本:

Simplified version of my c++ Class:

class Class
{
public:
    Class(uint32_t size_, uint8_t val_) buf(NULL), size(size_)
    {
         buf = new uint8_t[size];
         memset(buf, val_, size);
    }
    ~Class()
    {
        if(buf != NULL)
        {
            delete[] buf;
            buf = NULL;
            size = 0;
        }
    }
    void FakeDtor()
    {
        if(buf != NULL)
        {
            delete[] buf;
            buf = NULL;
            size = 0;
        }
    }

    protected:
        uint8_t* buf;
        uint32_t size;
}

我的单元测试代码:

TEST_F(Classtest, testDestructor) 
{
    Class *buff = new Class(10,10);
    ASSERT_NE(buff->getData(), (uint8_t*)NULL);

    buff->~Class(); // buff->FakeDtor();

    ASSERT_EQ(buff->getData(), (uint8_t*)NULL);
}

当我使用msbuild编译代码并运行UT时-显式调用dtor可以UT通过。当我使用g ++编译并使用gtest运行UT时-显式调用dtor似乎失败,因为以下声明失败。当我使用FakeDtor()代替〜Class()时,UT在Windows和Linuix上均通过。是什么导致dtor在Linux下显式调用时无法执行?

When I compile code using msbuild and run UT - explicit call to dtor works and UT passes. When I use g++ to compile and run UT using gtest - explicit call to dtor seems to fail because following assertion fails. When I Use FakeDtor() instead of ~Class() UT passes both on Windows and Linuix. What can cause dtor to not execute when calling it explicity under Linux?

推荐答案

在非平凡的类之后读取类的内容运行的析构函数调用未定义行为。没关系,对象所处的内存仍然存在,因为您没有删除它,对象本身已经死了,无法再使用。

Reading the contents of the class after its non-trivial destructor ran invokes Undefined Behavior. It does not matter that the memory the object lived in is still there because you did not delete it, the object itself is dead and can no longer be used.

从字面上看,无论如何都可以发生。手头的概念类似于悬挂指针/引用,例如,请参见

Literally everything is allowed to happen if you do it anyways. The concept at hand is similar to a dangling pointer/reference, for example see this.

此UB包含,如果析构函数设置了数据成员值,则由于没有有效的程序,要读取这些值,编译器可以优化这些成员的设置。 @hvd 在评论中。

这篇关于明确的析构函数调用不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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