1

I'm implementing a custom map class similar to the one from std, however I have one problem.In their map, when you do(for instance):

map<string, SomeObject*> container;
SomeObject* object = container["this doesn't exist"];

in the debugger object is 0x0000000, so invalid values from map are always null.However, in my map invalid values are like uninitialized pointers - they have an invalid value like 0xcdcdcdcd, however in Release mode its something else, so I cant rely to check for

if(object == 0xcdcdcdcd)

So I would like to be able to do this:

MyMap<string, SomeObject*> container;
SomeObject* object = container["this doesn't exist"]; //and for this to definetely be nullptr

so I can then do

if(object == nullptr)
   DoSomething();

I have a bool ContainsKey(KeyType key); function, but it involves a for loop.Is there some way to ensure what I want in initialization-time for the map, or do I have to make a custom PointerWrapper that will contain a pointer of SomeObject that is set to nullptr in PointerWrapper's constructor?I had a hard time figuring out what is going on in the std headers, they have an enormous amount of macros and typedefs.

ulak blade
  • 2,515
  • 5
  • 37
  • 81
  • 2
    `std::map<>` _value-initializes_ its values – see [this question/answer](http://stackoverflow.com/q/9025792/636019) for standardese. – ildjarn Mar 29 '13 at 21:39
  • 5
    The typical way to check for a key is map::find(key)!=map::end, rather than checking for default value. http://stackoverflow.com/questions/2333728/stdmap-default-value has an ok solution to your problem. – IdeaHat Mar 29 '13 at 21:41

3 Answers3

3

std::map value initializes any new values it creates internally. In the case of scalar types, this means they get initialized to 0.

Collin Dauphinee
  • 13,664
  • 1
  • 40
  • 71
3

Your values (for any type) will be initialized if you explicitly construct the object

SomeObject* object = SomeObject*();
//                              ^^ Explicit construction

For classes, the default constructor is obviously being called.

For built-in types like ints and pointers (like SomeObject*), they will be zero-initialized (instead of uninitialized)

So, whileyou could use = NULL in your specific pointer example, syntax like this will do The Right Thing for all types.

template < typename Key, typename Value >
void MyMap<Key, Value> add_new_key( const Key &k )
{
   std::pair<Key, Value>( k, Value() );
//                                ^^ Either calls constructor or zero-initializes

   // Store the data as you wish...
}
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
2

with std::map when you refer to an entry that doesnt exist it creates one and sets its value to be empty. For a pointer that means setting the value to null;

pm100
  • 48,078
  • 23
  • 82
  • 145