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; }
In C++, the delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer. It is an operator. It is a library function.
You don't need to delete it, and, moreover, you shouldn't delete it. If earth is an automatic object, it will be freed automatically. So by manually deleting a pointer to it, you go into undefined behavior. Only delete what you allocate with new .
Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed.
To make use of smart pointers in a program, you will need to include the <memory> header file. Smart pointers perform automatic memory management by tracking references to the underlying object and then automatically deleting that object when the last smart pointer that refers to that object goes away.
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! }
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