![]() |
Object's address and std::map
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? |
Re: Object's address and std::map
Am 16.03.2011 00:18, schrieb gusfonseca@yahoo.com:
> 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<my_class*, char> > 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 |
| All times are GMT. The time now is 03:50 PM. |
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.