By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,171 Members | 1,020 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,171 IT Pros & Developers. It's quick & easy.

STL Map in which the value type has no default constructor

P: n/a
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

Nov 6 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
dr*********@gmail.com wrote:
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
Nov 6 '06 #2

P: n/a
dr*********@gmail.com wrote:
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;
m.insert( std::map<int,X>::value_type( 5, X(5) ) );
}
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<>::operator[] 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
Nov 6 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.