显式调用析构函数不会破坏我的对象为什么? [英] explicit call to destructor is not destroying my object why?

查看:172
本文介绍了显式调用析构函数不会破坏我的对象为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我调用析构函数来释放内存,但它不是删除我的对象。其背后的原因是什么?

I'm calling the destructor to deallocate memory but it is not deleting my object. What is the reason behind it?

我的代码如下:

class A
{
public: 
    int a;
    A()
    {
        cout << "a" << endl;
    }
};

class B :public A
{
public: 
    int b;
    B()
    {
        cout << "b" << endl; a = 10; b = 20;
    }
    ~B()
    {
        cout << a << b << endl;
    }
};

,我使用它:

int main()
{
    {
        B b;
        b.~B();
        b.b=100;  // why this step is executed?
    }
    int x;
    cin>>x;
    return 0;
}


推荐答案


im调用析构函数来释放内存

i m calling destructor to deallocate memory

为什么?析构函数不释放对象占用的内存。从来没有。

Why? Destructor does not deallocate memory occupied by the object. Never did.

一个非平凡的析构函数结束对象的生命周期,但它不会结束对象的存储持续时间。这意味着内存保持分配,它只是变成原始(未初始化)。
所以,在这个意义上,它是销毁你的对象。

A non-trivial destructor ends object's lifetime, but it doesn't end the object's storage duration. This means that memory remains allocated, it just becomes "raw" (uninitialized). So, in that sense it is destroying your object.

同时,一个简单的析构函数根本没有效果。即使明确地调用它,对象的生命周期也不会结束。

Meanwhile, a trivial destructor has no effect at all. Even if you call it explicitly, the object's lifetime does not end.

在你的情况下,析构函数 B ::〜B 是不平凡的,正式意味着通过调用它结束了你的对象的生命。你毁了它,因为一个本地对象可以被销毁。 但记忆仍然存在。试图以 B 对象访问该内存只会导致未定义的行为。

In your case the destructor B::~B is non-trivial though, which formally means that by calling it you ended your object's lifetime. You destroyed it as much a local object can be destroyed. But the memory remains. Attempting to access that memory as a B object simply leads to undefined behavior.

事实上,没有办法手动释放本地对象占用的内存。本地内存总是自动释放。

In fact, there's no way to manually deallocate memory occupied by a local object. Local memory is always deallocated automatically.

这篇关于显式调用析构函数不会破坏我的对象为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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