Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent delete on pointer in C++

Tags:

c++

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; } 
like image 665
Mircea Ispas Avatar asked Aug 08 '12 14:08

Mircea Ispas


People also ask

Does delete only work on pointers?

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.

Do you need to delete pointers in C?

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 .

Does deleting a pointer delete the object?

Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed.

Do smart pointers automatically delete?

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.


1 Answers

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! } 
like image 117
Frerich Raabe Avatar answered Sep 28 '22 04:09

Frerich Raabe