开发者

Delete is a member function ? destructor in private won't be invoked with delete?

开发者 https://www.devze.com 2023-03-31 00:39 出处:网络
Given the next code : #include <iostream> using namespace std; class A { private: ~A () {} }; int main()

Given the next code :

#include <iostream>
using namespace std;

class A
{
private:
    ~A () {}
};

int main()
{

    A *a = new A();
    delete a;
    return 0;

}

It doesn开发者_运维百科't compile .I thought that delete is a member function , isn't ? If so , shouldn't it have access to the dtor of A ?

Regrads ,Ron


No, delete is not a member function; it's an operator. There is an operator delete() function which is invoked by the delete operator, but it's not a member unless you define it as such.


By that logic, this would be valid code:

class Foo
{
    Foo()
    {
    }
}

int main()
{
    // new is also a member function, right?
    Foo* Bar = new Foo;
}


Solution to the riddle: no, delete is not a member function

Delete is an operator, that can be overloaded for a type, but not as a member function


If you say to the compiler that a method is private, only the class can call it.

In you case, that means that only your class can delete itself.


This has nothing to do with the delete operator. Rather, the problem is that the destructor is private, and when you call the delete expression delete a;, this is equivalent to a->~A(); ::operator delete(a); It is this first call to the destructor that fails, rather than the call of the delete operator.

Even if you overloaded member new/delete operators, that wouldn't change a thing, because it's the delete expression which first calls the destructor and then the (member) operator, so the destructor must be available as a public function.


You are confusing the call to delete, with the implementation of the delete method.

If you call delete, actually 2 things will happen:

  • the destructor is called
  • the memory is freed

By default, the memory will be freed by a default delete method. If you implement the delete method, your implementation should only free the memory, not call any destructor.

That's why you need access to both the delete method AND the destructor before you can call delete.

0

精彩评论

暂无评论...
验证码 换一张
取 消