Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we call "delete this; " in a const-member function?

I saw the code snippet as follows:

class UPNumber {
public:
  UPNumber();
  UPNumber(int initValue);
  ...

  // pseudo-destructor (a const member function, because
  // even const objects may be destroyed)
  void destroy() const { delete this; } // why this line is correct???

  ...

private:
  ~UPNumber();
};

First, I am sure that above class definition is correct. Here is my question, why we can define the function 'destroy' as above? The reason being asking is that why we can modify 'this' in a const-member function?

like image 394
q0987 Avatar asked Feb 28 '11 23:02

q0987


People also ask

Can you call delete this inside a member function?

Answer: Yes, we can delete “this” pointer inside a member function only if the function call is made by the class object that has been created dynamically i.e. using “new” keyword. As, delete can only be applied on the object that has been created by using “new” keyword only.

Can const be deleted?

Any variable declared with let or const cannot be deleted from the scope within which they were defined, because they are not attached to an object.

Can you delete a pointer to const?

It is illegal to delete a variable that is not a pointer. It is also illegal to delete a pointer to a constant.

Can a const member function call a non-const function?

const member functions may be invoked for const and non-const objects. non-const member functions can only be invoked for non-const objects. If a non-const member function is invoked on a const object, it is a compiler error.


1 Answers

That works for the same reason that this work:

const int* upn = new int();
delete upn;

You can delete a pointer to a const-qualified object. The const-qualification on the member function just means that this has a type const UPNumber*.

like image 97
James McNellis Avatar answered Sep 20 '22 05:09

James McNellis