Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 Delete Class Type?

Tags:

c++

c++11

In C++11 N3485 5.3.5.1 it says:

The operand [of delete] shall be a pointer to object type or a class type. If of class type, the operand is contextually converted to a pointer to object type.

What is an example of such usage (operand is of class type)?

like image 628
Andrew Tomazos Avatar asked May 16 '13 11:05

Andrew Tomazos


1 Answers

If of class type, the operand is contextually implicitly converted to a pointer to object type.

So, you can use delete on object, but when and only when this type has implicit conversion operator to pointer.

class A
{
public:
   class Inner {};
   A()
   {
      inner = new Inner();
   }
   operator Inner*() { return inner; }
private:
   Inner* inner;
};

int main()
{
   A* a = new A();
   delete *a;
   delete a;
}

However, it's not new feature of C++11, in C++03 standard there are almost same words

The operand shall have a pointer type, or a class type having a single conversion function (12.3.2) to a pointer type.

like image 186
ForEveR Avatar answered Oct 01 '22 19:10

ForEveR