c++ - Destroy pointers to objects in array -
say want declare array of pointers specific object like
object *objects = new object[size]; and add new objects dynamically allocated array
for (int = 0; < size; i++){ object* obj = new obj; objects[i] = *obj; } is enough deallocate memory calling delete[] on array, or have loop through array first , call delete on each object? or stupid in practice?
first, have follow deallocation reverse order of allocation.
so number of times new many times delete , number of times new [] many times delete []
// assuming objects array of pointers [ object **objects ] (int = 0; < size; i++) { delete objects[i] ; } delete [] objects; and correct allocation should go as:
object **objects= new object*[size]; (int = 0; < size; i++) { objects[i] = new object; } also , should use smart pointers std::unique_ptr hassle free memory management
std::vector< std::unique_ptr<object> > objects ;
Comments
Post a Comment