删除调用析构函数但不删除对象? [英] Delete calling destructor but not deleting object?

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

问题描述

所以我一直使用c ++和指针一年半,现在,我认为我有他们的成功。我之前多次调用delete对象,对象实际上已被删除,或者至少我认为它们已经删除。

So I have been working with c++ and pointers for a year and a half now, and i thought i had them succeed. I have called delete on objects many times before and the objects actually got deleted, or at least i thought they did.

下面的代码只是混淆了我的地狱:

The code below is just confusing the hell out of me:

#include <iostream>

class MyClass
{
public:
    int a;

    MyClass() : a(10) {
        std::cout << "constructor ran\n";
    }

    void method(std::string input_) {
        std::cout << param_ << "\n";
    }

    ~MyClass() {
        std::cout << "destructor ran\n";
    }

};

int main()
{

   MyClass* ptr = new MyClass;

   ptr->method("1");

   delete ptr;

   ptr->method("2.5");

}

此代码输出:

constructor ran
1
destructor ran
2.5

我很困惑为什么它不会抛出任何类型的错误 - 我期待一个内存超出范围的异常或类似,但没有什么。 for 循环是在那里有一些隐藏的垃圾收集,即使我知道在c ++没有垃圾收集。

I was confused as to why it was not throwing an error of any sort - I was expecting a memory out of bounds exception or alike, but nothing. The for loop was in there incase there was some sort of hidden garbage collection, even though as far as I know there is no garbage collection in c++.

任何人都可以解释为什么这个代码工作,或者我错误的代码为它不给我的错误?

Can anyone explain as to why this code works, or where I am going wrong with this code for it not to give me the error?

推荐答案

你误解了 delete 是什么。所有 delete 是调用析构函数,并告诉分配器该内存是空闲的。它不会改变实际的指针。

You're misunderstanding what delete does. All delete does is call the destructor, and tell the allocator that that memory is free. It doesn't change the actual pointer. Anything beyond that is undefined.

在这种情况下,它对指向的实际数据没有任何影响。该指针指向之前指向的相同数据,并且调用它的方法工作正常。但是,这种行为不能保证;事实上,它明确未指定。 delete 可以清零数据;或者分配器可以为别的东西分配相同的内存,或者编译器可以拒绝编译这个。

In this case, it does nothing to the actual data pointed to. That pointer points to the same data it pointed to before, and calling methods on it works just fine. However, this behavior is not guaranteed; in fact, it's explicitly unspecified. delete could zero out the data; or the allocator could allocate that same memory for something else, or the compiler could just refuse to compile this.

C ++允许你做许多不安全的事情,性能。这是其中之一。如果你想避免这种错误,这是一个好主意:

C++ allows you to do many unsafe things, in the interest of performance. This is one of them. If you want to avoid this kind of mistake, it's a good idea to do:

delete ptr;
ptr = NULL;

,以确保不要尝试重用指针,比具有未定义的行为。

to ensure that you don't try to reuse the pointer, and will crash immediately if you do rather than having undefined behavior.

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

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