Object's address and std::map

G

gusfonseca

Is it safe to assume an object's address remains the same for the
duration of a program, once it is constructed?

For exemple, may i create a std::map<&my_class, char> and expect to
get the same 'char' upon passing an object's address ( my_char =
my_map[ my_pointer_to_object ] )?

If it is safe, is it also advisable to do so, or is it "evil" in some
way?
 
P

Peter Remmers

Am 16.03.2011 00:18, schrieb (e-mail address removed):
Is it safe to assume an object's address remains the same for the
duration of a program, once it is constructed?
An object's address remains the same for the duration of its lifetime.
Which may or may not be the same as the duration of the program. It
depends on the code you have written.

For exemple, may i create a std::map<&my_class, char> and expect to
I guess that should be std::map said:
get the same 'char' upon passing an object's address ( my_char =
my_map[ my_pointer_to_object ] )?

Yes. The map maps pointer values (addresses) to chars. The map will
always return the same char for the same pointer value (as long as you
don't modify that map entry). This is independent of the lifetime of the
object that happens to live (or have lived) at that address.
If it is safe, is it also advisable to do so, or is it "evil" in some
way?

The danger lies in the re-use of the address. If you destroy the object
and create a new one, the new one possibly happens to live at the same
address where some previous instance lived. Also, if you iterate over
the map and try to access the objects pointed to by the keys, these
objects better be still alive. The map should somehow be synchronized
with the lifetime of the objects. I.e. when an object gets deleted, make
sure you erase its address from the map.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top