Re: delete, hash_map
On 5 Mai, 00:57, SimpleCode <DragonXL...@gmail.com> wrote:
class COsgCar;
class moving_vechicle;
hash_map<moving_vechicle*, COsgCar*> m_hash;
hash_map<moving_vechicle*, COsgCar*>::iterator iter;
iter = m_hash.find( pMovingVechicle );
if ( iter != m_hash.end() )
{
COsgCar *p = m_hash[pMovingVechicle];
delete p;}
///////////////////////////////////////
It always run error.
But which one? Please provide the newsgroup with
all relevant information. A description like
"I have an error" is mostly the guarantee for little
response.
I don't know why.
I just test for some days.
There are at least four candidates. In every case I
assume that pMovingVechicle is of type moving_vechicle*
or at least implicitly convertible to that type. I guess
that point (4) is the most probable reason for your
problem, but check also the other of the following
guys:
1) As written COsgCar is an incompletly defined type.
Invoking delete on such type can cause UB. Ensure
that this type is defined *before* deletion to fix this
issue.
2) Since I don't know the definition of COsgCar
you should consider the possibility that it might be
the base class of some derived type as dynamic type.
Ensure that in this situation the actual base type
(at least COsgCar) has a virtual destructor, otherwise
UB takes place, because you invalidly invoke delete
on a dynamic type different from its static type.
3) You call delete (the scalar version) on some
pointer, but it's not obvious from the context,
which form of new was used for its allocation.
- Ensure that the deleted item was indeed created
via the scalar new form (*not* new[] and not any
other form of storage, e.g. storage of static
or automatic duration).
- Ensure that this pointer has not been deleted
before.
4) Your are invoking delete on a contained pointer of
the container m_hash. After this action any read
access to this pointer causes UB. Because the
container still *contains* this pointer, it's quite probable
that the container attempts to read it. To prevent this
problem, you have to divide the deletion into several
parts:
(a) Save the current pointer into a temporary pointer.
(b) Remove this pointer from the map (e.g. via
erase or the proper removal function)
(c) Invoke delete on the temporary pointer and don't
read that pointer after this!
If all this does not help, you should give the
community more information concerning the error,
which might lead to the conclusion that you need
to provide us with more details.
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]