Skip to main content
GameDev.net gamedev.net
🔒 Locked

list/vector/etc inside struct and delete

Started by u56237z Sep 6, 2010 at 5:28 AM 3 replies 1k views
Original Post
u56237z
u56237z
a rather silly question:

struct foo {
list l;
};

foo *ptr = new foo();

should I ptr->l.clear(); before deleting ptr? or may I take for granted that ptr->l will be automatically deallocated at ptr deletion?

I made a test and memory gets deallocated without leaks, but Im not sure it will work like this everywhere..
Zahlman
Zahlman
When you do not define a destructor, the default behaviour is to call the destructor for each data member and base class.(*)

In your case, there are no bases and the only data member is the list. The list's destructor will therefore be called. This destructor cleans up the list, so there is nothing to do.

You clean up your mess, and the standard library cleans up its mess.

* Even if you do define a destructor, these calls are made as well as running your destructor code. With well-written code using well-designed components, you will almost never have to do any work inside your own destructor - although you will have to at least define an empty, virtual destructor for a base class that will be used polymorphically.
u56237z
u56237z
thank you
_Kami_
_Kami_
note that this *will* leak memory

#include <iostream>#include <vector>#include <string>struct foo{  foo() {std::cout << "alloc\n";}  ~foo() {std::cout << "called\n";}  char meh;};struct bar{  std::vector<foo*> list;};int main (){  bar* bPtr = new bar();  bPtr->list.push_back(new foo());  bPtr->list.push_back(new foo());  bPtr->list.push_back(new foo());  delete bPtr;  return 1;}

output:
> ./a.out
alloc
alloc
alloc

so if you are storing pointers, you need to delete each pointer manually (by iterating over the list and call delete on the thing)
www.ageofconan.com
iMalc
iMalc
Quote:
Original post by _Kami_
so if you are storing pointers, you need to delete each pointer manually (by iterating over the list and call delete on the thing)
Which is why the standard advice given by most people nowdays is to not store raw pointers inside containers.
Using shared_ptr for example, would be part of the "well-written code using well-designed components" Zahlman was referring to.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.