Frage

I have a dynamic array (For this example, SIZE = 2):

polyTerm** polyn = new polyTerm* [SIZE];

I then add a few new ponlyTerm object to the array:

polyn[0] = new polyTerm(5.0,1);
polyn[1] = new polyTerm(2.0,1);

Now I want to remove the object from slot 0 and make the pointer null. How would I go about doing this? I currently have:

delete &polyn[0];

Then I use:

polyn[0] = NULL;

To make the pointer null.

Will this work?

EDIT: Correction, I need to use delete polyn[0] - even so, setting that to NULL should affect the pointer, as it would still technically point to the original location of the object. Resetting it to NULL removes any errors that could pop up later.

War es hilfreich?

Lösung

The code you've posted is correct.

The individual object pointer, polyn[0] was created using the non-[] version of new, and so must be deleted using the non-[] version of delete -- which is what you are doing.

I'd still recommend avoiding all of this in the first place however, and using vector <unique_ptr <polyTerm> > instead. Then all you have to do is erase whatever elements you want, or clear the entire vector without having to worry about using the correct type and number of new and delete.


I'll demonstrate using a vector of smart pointers here, neatly avoiding the lack of make_unique (until C++14) by using shared_ptr instead.

// Create array (vector)
vector <shared_ptr <polyTerm>> polyn; 
// Populate array
polyn.push_back (make_shared (5.0, 1));
polyn.push_back (make_shared (2,0, 1));
// Remove 0th element from array
polyn.erase (polyn.begin());
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top