Prevent delete on pointer in C++

You cannot declare a pointer to an arbitrary type in a way which prevents calling delete on the pointer. Deleting a pointer to const (T const*) explains why that is.

If it was a pointer to a custom class you could make the delete operator private:

class C {
    void operator delete( void * ) {}
};

int main() {
    C *c;
    delete c; // Compile error here - C::operator delete is private!
}

You certainly shouldn’t make the destructor private (as suggested by others) since it would avoid creating objects on the stack, too:

class C {
    ~C() {}
};

int main() {
    C c; // Compile error here - C::~C is private!
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)