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?
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.
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.
It is illegal to delete a variable that is not a pointer. It is also illegal to delete a pointer to a constant.
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.
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*
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With