473,769 Members | 5,449 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

the correct way to delete a map

Hi,

I have a map containing pointers. When I destroy the map I want to
delete
all the pointers.

typedef std::map<std::s tring, const T*Table;

void destroy_map ()
{
for (Table::iterato r i = table_.begin(); i != table_.end(); ++i)
{
delete (*i).second;
table_.erase (i);
}
}
this crashes. Does the erase() invalidate the iterator?

This was the code I found on the net (latout fixed a bit)

for (map::iterator itr = myMap.begin(); itr != myMap.end())
{
if(itr->value == something)
myMap.erase(itr ++);
else
itr++;
}

which it is claimed is from Josuttis. I suppose the fact that it
didn't compile should of made me doubt this...
--
Nick Keighley

Nov 8 '07 #1
17 50524
On 8 Nov, 10:55, Nick Keighley <nick_keighley_ nos...@hotmail. com>
wrote:
Hi,

I have a map containing pointers. When I destroy the map I want to
delete
all the pointers.

typedef std::map<std::s tring, const T*Table;

void destroy_map ()
{
for (Table::iterato r i = table_.begin(); i != table_.end(); ++i)
{
delete (*i).second;
table_.erase (i);
}

}

this crashes. Does the erase() invalidate the iterator?

This was the code I found on the net (latout fixed a bit)

for (map::iterator itr = myMap.begin(); itr != myMap.end())
{
if(itr->value == something)
myMap.erase(itr ++);
else
itr++;

}

which it is claimed is from Josuttis. I suppose the fact that it
didn't compile should of made me doubt this...
ah! more poking around on the net. erase() does invalidate the
iterator. That's why the net code does a post increment in the erase
call.
So preumably I want:-

void destroy_map ()
{
for (Table::iterato r i = table_.begin(); i != table_.end();)
{
delete (*i).second;
table_.erase (i++);
}
}

since this code is actually in a DTOR and table_ is member variable
would I be better leaving the destruction of the map to the DTOR?

class Symbol_table
{
public:
Table table_;
~Symbol_table() ;
};

Symbol_table::~ Symbol_table()
{
for (Table::iterato r i = table_.begin(); i != table_.end(); ++i)
delete (*i).second;
}

should the for-loop be changed into an algorithm? for_each()?
--
Nick Keighley

Nov 8 '07 #2
Nick Keighley wrote:
table_.erase (i++);
No, the standard way is: i = table_.erase(i) ;

Besides, there's no need to individually erase the map elements. Just
free the memory pointed by the elements and then just clear() the map,
given that you are cleaning it completely.
Nov 8 '07 #3
Nick Keighley <ni************ ******@hotmail. comwrote:
I have a map containing pointers. When I destroy the map I want to
delete all the pointers.

typedef std::map<std::s tring, const T*Table;

void destroy_map ()
{
for (Table::iterato r i = table_.begin(); i != table_.end(); ++i)
{
delete (*i).second;
table_.erase (i);
}
}
this crashes. Does the erase() invalidate the iterator?
Yes. Try this instead:

void destroy_map()
{
for ( Table::iterator i = table_.begin(); i != table_.end(); ++i )
{
delete i->second;
i->second = 0; // I don't think this is strictly necessary...
}
table_.clear();
}

or if you want to have fun with algorithms:

typedef map<int, int*Table;

template < typename T >
void delete_second( T& t ) {
delete t.second;
t.second = 0;
}

void destroy_map()
{
for_each( table_.begin(), table_.end(),
&delete_second< Table::value_ty pe);
table_.clear();
}
Nov 8 '07 #4
Nick Keighley wrote:
On 8 Nov, 10:55, Nick Keighley <nick_keighley_ nos...@hotmail. com>
wrote:
>Hi,

I have a map containing pointers. When I destroy the map I want to
delete
all the pointers.

typedef std::map<std::s tring, const T*Table;

void destroy_map ()
{
for (Table::iterato r i = table_.begin(); i != table_.end(); ++i)
{
delete (*i).second;
table_.erase (i);
}

}

this crashes. Does the erase() invalidate the iterator?

This was the code I found on the net (latout fixed a bit)

for (map::iterator itr = myMap.begin(); itr != myMap.end())
{
if(itr->value == something)
myMap.erase(itr ++);
else
itr++;

}

which it is claimed is from Josuttis. I suppose the fact that it
didn't compile should of made me doubt this...

ah! more poking around on the net. erase() does invalidate the
iterator. That's why the net code does a post increment in the erase
call.
So preumably I want:-

void destroy_map ()
{
for (Table::iterato r i = table_.begin(); i != table_.end();)
{
delete (*i).second;
table_.erase (i++);
}
}

since this code is actually in a DTOR and table_ is member variable
would I be better leaving the destruction of the map to the DTOR?
It definitely would. And I'll tell you more, that if you use a smart
pointer you can also forget about the deallocation. The bad thing is
that you need to use additional libraries, such as boost.

Then you can have something as:

#include <map>
#include <boost/shared_ptr.h>

typedef boost::shared_p tr<intElementPt r;
typedef std::map<int, ElementPtrTable ;

int main(){
Table t;
t[1] = ElementPtr(new int(1));
t[2] = ElementPtr(new int(2));
}

this will be correctly deleted by the map destructor.

Regards,

Giuseppe


Nov 8 '07 #5
Nick Keighley <ni************ ******@hotmail. comwrote:
ah! more poking around on the net. erase() does invalidate the
iterator. That's why the net code does a post increment in the erase
call.
So preumably I want:-

void destroy_map ()
{
for (Table::iterato r i = table_.begin(); i != table_.end();)
{
delete (*i).second;
table_.erase (i++);
}
}

since this code is actually in a DTOR and table_ is member variable
would I be better leaving the destruction of the map to the DTOR?

class Symbol_table
{
public:
Table table_;
~Symbol_table() ;
};

Symbol_table::~ Symbol_table()
{
for (Table::iterato r i = table_.begin(); i != table_.end(); ++i)
delete (*i).second;
}

should the for-loop be changed into an algorithm? for_each()?
Let the destructor take care of the map, unless you find yourself
putting this kind of loop in all over the place.

I showed in another post how to switch it to using for_each, but I'm not
sure of the utility. I can't think off-hand of any other uses for the
functor, so the only gain would be the removal of the loop.

If, however, you find you have to go through maps like this more than
once in your program, then you should probably write a separate function
for it.

template < typename Map >
void delete_map_ptrs ( Map& m ) {
for ( Map::iterator it = m.begin(); it != m.end(); ++it )
{
delete it->second;
it->second = 0;
}
}
Nov 8 '07 #6
Juha Nieminen wrote:
Nick Keighley wrote:
> table_.erase (i++);

No, the standard way is: i = table_.erase(i) ;

Besides, there's no need to individually erase the map elements. Just
free the memory pointed by the elements and then just clear() the map,
given that you are cleaning it completely.
Sorry, Juha, but map<>::erase returns void.
Nov 8 '07 #7
red floyd wrote:
Juha Nieminen wrote:
>Nick Keighley wrote:
>> table_.erase (i++);

No, the standard way is: i = table_.erase(i) ;

Besides, there's no need to individually erase the map elements.
Just free the memory pointed by the elements and then just clear()
the map, given that you are cleaning it completely.

Sorry, Juha, but map<>::erase returns void.
In C++0x it will return an iterator. Many library implementations
already have that. While in the currect Standard it's 'void', check
your implementation for it as a possible extension.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 8 '07 #8
On Nov 8, 2:38 pm, Juha Nieminen <nos...@thanks. invalidwrote:
Nick Keighley wrote:
table_.erase (i++);
No, the standard way is: i = table_.erase(i) ;
Sorry, Juha, but for some silly reason, map<>::erase() doesn't
return an iterator. (This will be corrected in the next version
of the standard, and I think some implementations already
support it, but if you want to be portable and/or standards
conformant, you can't do it.)
Besides, there's no need to individually erase the map elements. Just
free the memory pointed by the elements and then just clear() the map,
given that you are cleaning it completely.
Formally, having a pointer to a deleted object in the map is
undefined behavior. So you really have to either erase or null
the pointer in the map before deleting, something like:
T* tmp = *i ;
table.erase( i ++ ) ;
delete tmp ;
or
T* tmp = NULL ;
std::swap( tmp, *i ) ;
delete tmp ;
(And that's really in code---using swap is definitly stylish.)

Practically, of course, I wouldn't worry about it, and would do
it as you suggest. Or use smart pointers: the case where a
container is the actual owner of an object is one of the cases
where their use is justified. (I'll admit that in my own code,
in almost 20 years of C++, I've only found one case where a
container actually owned something it pointed to. But that's a
different issue.)

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Nov 9 '07 #9
On 9 Nov, 09:38, James Kanze <james.ka...@gm ail.comwrote:

<snip>
Formally, having a pointer to a deleted object in the map is
undefined behavior. So you really have to either erase or null
the pointer in the map before deleting
<snip>
Practically, of course, I wouldn't worry about it, and would do
it as you suggest. Or use smart pointers: the case where a
container is the actual owner of an object is one of the cases
where their use is justified. (I'll admit that in my own code,
in almost 20 years of C++, I've only found one case where a
container actually owned something it pointed to. But that's a
different issue.)
well obviously I can't disagree with your experience. But it seemed
not unusual for a container to own an object it pointed to. If you're
newing a lot of similar objects then you need to keep them somewhere.
Why not a container?

The code that prompted my original query was a symbol table.
A definition file is parsed to build the symbol table

typedef std::map<std::s tring,const Type*Table;

This symbol table is then used to decode a stream of data.
The first octet read is looked up to yield the message name,
which is then looked up to find the Type. Type knows how
to parse the rest of the stream.

Other cases might be Calls in a telecommunicati on system.
Drawable items in a drawing program etc.

I'd have thought a container that owned things it pointed to was
very common!
--
Nick Keighley

Nov 9 '07 #10

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

Similar topics

2
5407
by: Ian McBride | last post by:
(was: delete() confusion) I have a class with multiple base classes. One of these base classes (base1) has its own new/delete operators and nothing else. Another base class (base 2) has a virtual destructor. The class with the virtual destructor has AddRef() and Release() methods, and Release() ultimately does a "delete this". Can that "delete this" statement somehow find the right delete method? If it does, it involves a downcast...
8
2528
by: Randy Gordon | last post by:
Say I do the following: char **names = new char*; for (int i = 0; i < 100; i++) { names = new char; } When I'm done with the array of character pointers, how should I delete it? Like this:
1
3848
by: Nimmi Srivastav | last post by:
There's a rather nondescript book called "Using Borland C++" by Lee and Mark Atkinson (Que Corporation) which presents an excellent discussion of overloaded new and delete operators. In fact there are quite a few things that I learned that I did not know before. For example, while I knew that the new and delete operators can be overloaded for classes, I did not know that that the global new and delete operators can also be overloaded. ...
3
9413
by: Nimmi Srivastav | last post by:
There's a rather nondescript book called "Using Borland C++" by Lee and Mark Atkinson (Que Corporation) which presents an excellent discussion of overloaded new and delete operators. I am presenting below a summary of what I have gathered. I would appreciate if someone could point out to something that is specific to Borland C++ and is not supported by the ANSI standard. I am also concerned that some of the information may be outdated...
3
281
by: Christian Meier | last post by:
Hi NG I don't know if this problem is system dependend but I don't think so. So, here is my assumption: "delete" deletes a variable. "delete" deletes an array. Is this correct so far? And now check this code out: #include <iostream> using namespace std;
4
9409
by: Stephen | last post by:
Hello People, Using MS Access 2003 VBA I get the error 3020 Update or CancelUpdate without AddNew or Edit when I run through the following code. Can anyone help suggest anything to try? Thanks. On Error GoTo delete_failed Dim RS_DEL As DAO.Recordset
10
1889
by: junw2000 | last post by:
Hi, Below is a small code about memory allocation and deallocation. #include <cstdlib> #include <iostream> using namespace std; class X { public: void* operator new(size_t sz) throw (const char*) {
5
8092
by: mkaushik | last post by:
Hi everyone, Im just starting out with C++, and am curious to know how "delete <pointer>", knows about the number of memory locations to free. I read somewhere that delete frees up space assigned to <pointerby "new". Does "new" create a list of pointer names and the size of the memory array they point to? I also read that some compilers may store the number of consec mem locations a pointer points to, just before the first data...
1
1632
by: Gonçalo Rodrigues | last post by:
Hi all, I am a little confused about the delete operator, so I have a question. Suppose we have something like class Base { public: void* operator new(std::size_t size); void operator delete(void* ptr);
1
1522
by: rasmidas | last post by:
I have a similar kind of code as below. But I could not guess how to delete. Please help me. #include<stdio.h> #include<string.h> #include<stdlib.h> int main() { char* items; int i; for(i=0;i<5;i++)
0
9590
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9424
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
10223
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
9866
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...
0
8879
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7413
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
5310
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...
1
3968
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2815
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.