I am using an object factory with a function to create and register new objects :
Object * MyObjectFactory::createNewObject()
{
Object * my_object = new Object();
m_vector_of_objects.push_back(my_object);
return my_object;
}
I am now writing the delete operator, where I just loop through the vector and delete all the objects, and I am wondering if there is a difference between :
MyObjectFactory::~MyObjectFactory()
{
// Destroy memory allocated objects
for (auto * my_object : m_vector_of_objects)
{
delete(my_object);
}
}
and
MyObjectFactory::~MyObjectFactory()
{
// Destroy memory allocated objects
for (auto &my_object : m_vector_of_objects)
{
delete(my_object);
}
}
Is it actually de-allocating memory in both case ?
Is it actually de-allocating memory in both case ?
Yes. There is no difference between deleting a copy of a pointer and deleting a the same pointer through a reference. Latter introduces a redundant layer of indirection (which is probably optimised away).
PS Owning bare pointers are a bad design. Prefer smart pointers and consider whether Object
s need separate storage in the first place.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.