the swine
the swine

Reputation: 11031

Default value of a pointer in a new std::map entry

So I have the following std::map:

std::map<int, float*> map;

This map is accessed using its operator []:

float *pointer = map[123];

Now if the key 123 did not exist in the map, the value of the pointer will be undefined. Is that correct? To make sure it is:

template <class T>
struct PtrWithDefault {
    T *p;
    PtrWithDefault() :p(0) {} // default
    PtrWithDefault(T *ptr) :p(ptr) {}
    PtrWithDefault(PtrWithDefault other) :p(other.p) {} // copy
    operator T *() { return p; }
};
std::map<int, PtrWithDefault<float> > map;

Now doing the same ensures the correct initialization of the pointer. Is there other way around it? This is kind of ugly solution. My ultimate aim is speed:

std::map<int, float*> map;
float *p;
std::map<int, float*>::iterator it = map.find(123);
if(it != map.end())
    p = (*it).second; // just get it
else
    map[123] = p = 0;

Is this going to be faster than the solution with default pointer? Are there better ways to do this?

EDIT

Ok, this was completely silly of me. As Brian Bi correctly says, the pointer will be initialized automatically, due to zero-initialization. Value initialization is there since C++03, while C++98 (which is the only available standard in Visual Studio 2008) does not have that.

Anyway, it is readily verified as:

std::map<int, float*> map;
typedef float *P;
float *p = map[123], *p1 = P();

Both p and p1 are indeed null, no need to worry about a thing.

Upvotes: 3

Views: 1538

Answers (1)

Brian Bi
Brian Bi

Reputation: 119219

If the key is not found in the map, the inserted value is value-initialized (§23.4.4.3/1). So no need for a wrapper; the pointer inserted will be a null pointer.

Upvotes: 10

Related Questions