Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

c++ - STL map containing references does not compile

The following:

std::map<int, ClassA &> test;

gives:

error C2101: '&' on constant

While the following

std::map<ClassA &, int> test;

gives

error C2528: '_First' : pointer to reference is illegal

The latter seems like map cannot contain a reference for the key value, since it needs to instantiate the class sometimes and a reference cannot be instantiated without an object. But why does the first case not work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is illegal to store references in an stl container, because types must be copy constructible and assignable. References can not be assigned.

Exactly what operation causes the first error is implementation dependent, but I image that it is related to creating a reference and not assigning it immediately. The second error message looks like its actually related to building the map index.

If your type is small, you can copy it into the map, or if it is large consider using pointers instead, but remember that the container will not deallocate the objects for you, you'll have to do that explicitly yourself.

This SO question might be of interest to you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...