Are new std::map elements initialized?

I

int2str

Hi!

Given the following code:

#include <map>
#include <string>
#include <cassert>

int main()
{
std::map< std::string, unsigned > my_map;
++my_map["Test"];

assert( my_map["Test"] == 1 );
}

Can I rely on the fact that the newly created map element with key
"Test" will be created with a value of 0?

Josuttis's "The C++ Standard Library" seems to indicate so (pg. 207).

The Standard briefly states (23.3.1.2 para 1):

T& operator[] (const key_type& x);

Returns: (*((insert(make_pair(x, T()))).first)).second

So it looks like the default constructor for T is called. For PODs like
"unsigned", does the default constructor (?) guarantee
0-initialization?

Thanks for your insights!

Cheers,
Andre
 
G

Gregory

As I know there is no such thing as default constructor for C/C++ basic
types.

Try

void foo()
{
int i, j; // no default constructor
}

Neither i nor j are assigned 0. They both are uninitialized (junk).

Gregory
 
R

red floyd

Gregory said:
As I know there is no such thing as default constructor for C/C++ basic
types.

Try

void foo()
{
int i, j; // no default constructor
}

Neither i nor j are assigned 0. They both are uninitialized (junk).

Gregory

but i = int() does initialize to 0.
So, If a map uses:
return (*((insert(make_pair(x, T()))).first)).second
as Josuttis claims, then if T is int, then the make_pair() call with
int() as the second parameter creates a pair with 0 as the second element.
 
G

Gregory

Yes, you are right. I wrote a test and my_map["Test"] returned 0.
I also checked g++ STL implementation we have and indeed
map::eek:perator[] calls integer constructor - int() as you said.

_Tp& operator[](const key_type& __k) {
iterator __i = lower_bound(__k);
// __i->first is greater than or equivalent to __k.
if (__i == end() || key_comp()(__k, (*__i).first))
__i = insert(__i, value_type(__k, _Tp()));
return (*__i).second;
}


Gregory
 
J

Jonathan Mcdougall

Hi!

Given the following code:

#include <map>
#include <string>
#include <cassert>

int main()
{
std::map< std::string, unsigned > my_map;
++my_map["Test"];

assert( my_map["Test"] == 1 );
}

Can I rely on the fact that the newly created map element with key
"Test" will be created with a value of 0?

Yes. std::map::eek:perator[] returns (*((insert(make_pair(x,
T()))).first)).second and T() default-initializes an object. For
non-PODs, the default ctor is called; for arrays, each element is
default-initialized; other types are zero-initialized.


Jonathan


Jonathan
 

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

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top