Is it possible to delete an object in C ++ without calling the destructor?

I have an object with some pointers inside it. The destructor calls deletefor these pointers. But sometimes I want to delete them, and sometimes not. Therefore, I would like to delete the object without calling the destructor. Is it possible?

Editing: I understand that this is a SIMPLE idea that no one should ever do. However, I want to do this because it will make some internal functions much easier to write.

+5
source share
7 answers

You can set pointers to NULL, then the destructor will not delete them.

struct WithPointers
{
    int* ptr1;
    int* ptr2;

    WithPointers(): ptr1(NULL), ptr2(NULL) {}

    ~WithPointers()
    {
        delete ptr1;
        delete ptr2;
    }
}

...
WithPointers* object1 = new WithPointers;
WithPointers* object2 = new WithPointers;
object1->ptr1 = new int(11);
object1->ptr2 = new int(12);
object2->ptr1 = new int(999);
object2->ptr2 = new int(22);
...
int* pointer_to_999 = object2->ptr1;
object2->ptr1 = NULL;
delete object1;
delete object2; // the number 999 is not deleted now!
// Work with the number 999
delete pointer_to_999; // please remember to delete it at the end!
+7
source

An operator deletedoes two things to the object you pass to it:

  • .
  • , operator delete.

, , operator delete :

Foo *f = new Foo;
operator delete(f);

operator delete . delete operator delete. , delete - operator delete, . , , , operator delete.

, operator delete - . RAII, . undefined. , RAII, . .

+7

Eww! , , , . , , - . ++, ...

+4

, . , boolean, , .

, , ( , , - , ).

+2

, . boolean. destuctor, , , , .

. .

+2

, , [ - std::string std::vector , ]. - (, / ), , , .

+1

, . std::vector , , ( ) , .

++ 11 union /, , , . , , . new, .

union, N 1, . union , ( ).

However, the likelihood is that the real answer to your question is "don't do this." And if you do, you will wrap the pointers in class, whose only task is to handle the above mess. Classes of this type (whose task is to control the pointer's lifetime and pointer properties) are called smart pointers.

+1
source

All Articles