STL Map in which the value type has no default constructor

D

drsantosh82

Hi,

Is it possible to have an STL map in which the value type (i.e. the
"second" of the pair) does not have an overloaded constructor?

For example, I have a map definition like this:
map<size_t, MyClass> my_map;

but MyClass does not have a default constructor.

Is it possible to define the map in this way? If yes, could someone
kindly post a sample code snippet?

I am getting a linker error when I have any code that attempts to
insert into this map. As long as I leave the map alone, I am not
getting any linker error.

Thanks,
Santosh
 
S

Stuart Redmann

Hi,

Is it possible to have an STL map in which the value type (i.e. the
"second" of the pair) does not have an overloaded constructor?

Nope. The C++ standard states that the value type of std::map must be
assignable (which includes that it must be copy-constructable). Also it
must be default constructable.
For example, I have a map definition like this:
map<size_t, MyClass> my_map;

but MyClass does not have a default constructor.

Then define one. If your class doesn't support this semantics, you may
think about storing pointers to your class in the map.
I am getting a linker error when I have any code that attempts to
insert into this map.

You're most probably getting a compiler error, or else you have defined
the constructors, but have given no implementation.
As long as I leave the map alone, I am not
getting any linker error.

That's how templates work: you only get the code you're actually needing.

Regards,
Stuart
 
K

Kai-Uwe Bux

Hi,

Is it possible to have an STL map in which the value type (i.e. the
"second" of the pair) does not have an overloaded constructor?

For example, I have a map definition like this:
map<size_t, MyClass> my_map;

but MyClass does not have a default constructor.

Is it possible to define the map in this way? If yes, could someone
kindly post a sample code snippet?

#include <map>

class X {

X();

public:

X ( int i ) {}

};


int main ( void ) {
std::map< int, X > m;
I am getting a linker error when I have any code that attempts to
insert into this map. As long as I leave the map alone, I am not
getting any linker error.

std::map<>::eek:perator[] requires the mapped_type to be default constructible.
However, I do not think that the other operations do. In any case, you
should get a compiler error, not a linker error. Post code.


Best

Kai-Uwe Bux
 

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,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top