Is there any way to prevent deleting a pointer in C++ by its declaration?
I’ve tried following code without luck.
const int* const foo()
{
static int a;
return &a;
}
int main()
{
const int* const a = foo();
*a = 1; //compiler error, const int*
a++; //compiler error, int* const
delete a; //no compiler error, I want to have compiler error here
return 0;
}
You cannot declare a pointer to an arbitrary type in a way which prevents calling
deleteon 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
deleteoperator private:You certainly shouldn’t make the destructor private (as suggested by others) since it would avoid creating objects on the stack, too: