Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor C++: type '***' argument given to 'delete', expected pointer

Tags:

c++

destructor

I declared a private variable

vector<SomeClass> theVector;

someplace inside my SomeClass class.

Why can't I say: delete theVector inside my SomeClass destructor?

The compiler error says:

 type `class Vector<SomeClass>' argument given to `delete', expected pointer 

What expected pointer?

like image 379
andandandand Avatar asked Dec 20 '08 02:12

andandandand


People also ask

Does deleting a pointer delete the object?

delete keyword in C++Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed. The delete operator has void return type does not return a value.

How do you delete a pointer in C++?

delete and free() in C++ 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.

What happens when you delete a pointer C++?

The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area).

How does delete work in C++?

When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.


1 Answers

If new and delete go hand in hand.

To delete something you need to create it via new (which gives you a pointer). You can then delete the pointer. The way you are declaring the vector it is being created on the stack (not the heap) and will be deallocated when it goes out of scope.

int main()
{
    vector<SomeClass> theVector;

    vector<SomeClass>* ptrVctor = new vector<SomeClass>();


    delete ptrVctor;   // ptrVctor must be deleted manually
    // theVector destroyed automatically here
}
like image 104
Martin York Avatar answered Sep 16 '22 18:09

Martin York