473,659 Members | 3,420 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

delete pointers in destructor

Hi,

Switching some code from C to C++, and I have a destructor question:

In the C code, when the program wants to close and free all memory, I
have them call a Close function. The linked-lists get free'd.

In the C++ versions, my class has a linked list items of another
class, which also has a linked list of another class. I was going to
add a Close function to the classes, but is the C++ way to just put
the delete statements in the destructor and let it get handled
automatically?

Thanks in advance,
T
Dec 19 '07 #1
8 4985
TBass wrote:
Switching some code from C to C++, and I have a destructor question:

In the C code, when the program wants to close and free all memory, I
have them call a Close function. The linked-lists get free'd.

In the C++ versions, my class has a linked list items of another
class, which also has a linked list of another class. I was going to
add a Close function to the classes, but is the C++ way to just put
the delete statements in the destructor and let it get handled
automatically?
Usually, yes. There are exceptions, of course. If you actually use
'std::list' as your member, you don't need to delete anything, the
list will take care of that. The exceptions to that rule is if your
list is of pointers to dynamically created objects. The rule is, if
you obtained the pointer through 'new' (or 'new[]'), you must dispose
of it using 'delete' (or 'delete[]'). The exception to that rule, in
turn, is if you're using some kind of "smart" pointer type to hold
the naked pointer for you.

Perhaps if you're most specific in your question, you'd get a more
specific answer :-)

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Dec 19 '07 #2
Sorry. I didn't mean to be vague.

[snip]
The exceptions to that rule is if your list is of pointers to
dynamically created objects.
[/snip]

I am using std::list, but it is a list of pointers to an instance of
the class, which I created with the new statement.

Here's a quick outline of what I'm doing:

class tag
{
...
}

class device
{
...
std::list<tag *m_listTags
}
device::AddTag
{
tag *mytag = new tag;
m_listTags.push _back( mytag );
}
class project
{
...
std::list<devic e *m_listDevices
}

project::AddDev ice
{
device *mydevice = new device;
m_listDevices.p ush_back( device );
}
So I'm thinking I should just add to the destructors:

device::~device (void)
{
std::list<tag *>::iterator item;
device *mytag;
for ( item = m_listTags.begi n(); item != m_listTags.end( ); +
+item )
{
mytag = *item;
delete mytag
}

m_listTags.empt y()
}

project::~proje ct(void)
{
std::list<devic e *>::iterator item;
device *mydevice;
for ( item = m_listDevices.b egin(); item != m_listDevices.e nd(); +
+item )
{
mydevice = *item;
delete mydevice
}

m_listDevices.e mpty()
}

Thanks!
T
Dec 19 '07 #3
TBass wrote:
Sorry. I didn't mean to be vague.

[snip]
The exceptions to that rule is if your list is of pointers to
dynamically created objects.
[/snip]

I am using std::list, but it is a list of pointers to an instance of
the class, which I created with the new statement.
Do you really need to? What if you keep a list of tags or list of
devices instead? 'std::list' creates its elements dynamically
anyway. Let your lists manage memory.

If you _have to_ keep a list of pointers, you're doing it correctly,
with a bit of excess, see below.
>
Here's a quick outline of what I'm doing:

class tag
{
...
}

class device
{
...
std::list<tag *m_listTags
Why not change it to

std::list<tagm_ listTags;

?
}
device::AddTag
{
tag *mytag = new tag;
m_listTags.push _back( mytag );
In case you decide to change, you would just do

m_listTags.push _back(tag());

Isn't it better?
}
class project
{
...
std::list<devic e *m_listDevices
Same here, why not just

std::list<devic em_listDevices;

? I know one possible answer, but I don't want to speculate.
}

project::AddDev ice
{
device *mydevice = new device;
m_listDevices.p ush_back( device );
}
So I'm thinking I should just add to the destructors:
Below my comments assume you still go with the lists of pointers.
>
device::~device (void)
{
std::list<tag *>::iterator item;
device *mytag;
^^^^^^^^^^^^^
You don't need this.
for ( item = m_listTags.begi n(); item != m_listTags.end( ); +
+item )
{
mytag = *item;
^^^^^^^^^^^^^^
You don't need this either.
delete mytag
Change it to

delete *item;
}

m_listTags.empt y()

No need to empty, it's about to be destructed.
}

project::~proje ct(void)
{
std::list<devic e *>::iterator item;
device *mydevice;
Same thing. No need for this local var.
for ( item = m_listDevices.b egin(); item != m_listDevices.e nd(); +
+item )
{
mydevice = *item;
delete mydevice
Just do

delete *item;

instead.
}

m_listDevices.e mpty()
No need to empty, it's about to be destructed.
}

Thanks!
T
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Dec 19 '07 #4
On Wed, 19 Dec 2007 07:33:38 -0800 (PST) in comp.lang.c++, TBass
<tb*@automatedd esign.comwrote,
>I am using std::list, but it is a list of pointers to an instance of
the class, which I created with the new statement.
You should look carefully at whether you really need to do that, or
if you can just use a list of the instances.
Dec 19 '07 #5
Do you really need to? What if you keep a list of tags or list of
devices instead? 'std::list' creates its elements dynamically
anyway. Let your lists manage memory.
Agreed, which is what I originally intended. However, I have to pass
out pointers to instances of the class to forms for display and
editing. I wasn't sure how this would affect the list, or if changes
to the list in other functions could cause an address I had previously
passed out to become invalid, so I figured I would play it safe.

device *mytag;

^^^^^^^^^^^^^
You don't need this.
for ( item = m_listTags.begi n(); item != m_listTags.end( ); +
+item )
{
mytag = *item;

^^^^^^^^^^^^^^
You don't need this either.
delete mytag

Change it to

delete *item;
}
m_listTags.empt y()

No need to empty, it's about to be destructed.
Great. Thanks for the tips.

Very much appreciated,
T
Dec 19 '07 #6
On 2007-12-19 17:32, TBass wrote:
>Do you really need to? What if you keep a list of tags or list of
devices instead? 'std::list' creates its elements dynamically
anyway. Let your lists manage memory.

Agreed, which is what I originally intended. However, I have to pass
out pointers to instances of the class to forms for display and
editing. I wasn't sure how this would affect the list, or if changes
to the list in other functions could cause an address I had previously
passed out to become invalid, so I figured I would play it safe.
The list is node-based, a pointer to an element will be valid as long as
you do not delete that element, regardless of what you do with the rest
of the elements in the list. This is not true for all containers though.

--
Erik Wikström
Dec 19 '07 #7
TBass <tb*@automatedd esign.comwrote in news:7712834f-c002-421c-9189-
df**********@a3 5g2000prf.googl egroups.com:
Hi,

Switching some code from C to C++, and I have a destructor question:

In the C code, when the program wants to close and free all memory, I
have them call a Close function. The linked-lists get free'd.

In the C++ versions, my class has a linked list items of another
class, which also has a linked list of another class. I was going to
add a Close function to the classes, but is the C++ way to just put
the delete statements in the destructor and let it get handled
automatically?
If I understand correctly, yes. Your class initiates the deletion of your
linked list (which I'd hope is in some appropriate class itself, like
std::list<>). Your linked list will know how to dispose of itself. Your
"other object" would know to dispose of the linked list it contains.
Dec 19 '07 #8
Indeed, generally, it is better to store the objects, rather than the
pointer to the object in the container.
However, in some cases this is not the solution. For example, when you
want to store instances of different classes with common base class.
Another example ( although very rare ) is when copying the object
( i.e. copy constructor ) is very expensive in means of time or
allocated resources.
In those cases, it could be useful to store smart pointers in your
container.
This way you get the advantage of using pointers, without the need to
delete the instances in the container.

My 2 cents
Dec 20 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

52
26996
by: Newsnet Customer | last post by:
Hi, Statement 1: "A dynamically created local object will call it's destructor method when it goes out of scope when a procedure returms" Agree. Statement 2: "A dynamically created object will call it's destructor when it is made a target of a delete".
6
3369
by: Gandalf | last post by:
Hello. I have some questions about the standard containers. How does the standard containers behave if I do queue<Foo> myQ; queue<Foo> myQ2; .... insert into myQ... myQ = myQ2;
10
1463
by: John | last post by:
Hi: I have a question from the book---C++ primer, page 677. char *arena = new char; Image *ptr = new (arena) Image( "Quasimodo" ); After the above two lines, arena and ptr point to the same memory. If I "delete arena", that memory will be released, right? Is ptr an dangling pointer now?
1
3884
by: Douglas Peterson | last post by:
class Allocator { public: virtual void * Alloc(size_t) = 0; virtual void * Free(void*) = 0; }; class Object { public:
6
1992
by: R.Z. | last post by:
i'm using a class from some api that is said to automatically call its destructor when its out of scope and deallocate memory. i create instances of this class using "new" operator. do i have to explicitly call delete on these instances when i no longer need them?
7
16493
by: morz | last post by:
i just search for a while in c++ groups but cannot find good answer. i have code like this: int **ptr; ptr = new char *; ptr = new int(5); ptr = new int(16);
27
7182
by: fermisoft | last post by:
I have a strange problem in my project. I have a class like this...... class CMsg { public: void *m_body; ~CMsg()
6
1881
by: mdinino | last post by:
Hi, I am new to C++, and I have a simple question but I can't seem to find a direct answer. If I use new to create something in the scope of a function and then I return the pointer that I get to another function, do I need to worry about the memory space being used by anything else and causing the program to crash?
5
2109
by: Renato | last post by:
I have an array of pointers to class Shape. I create 4 items and display their values. shapes Shape *shapes; shapes = new Shape (p1); shapes = new Triangle (p1); shapes = new Polygon (p2);
0
8337
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8628
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6181
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5650
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4335
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1978
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1739
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.