C++: Is it possible to use a reference as the valu

2019-01-26 05:23发布

问题:

Is it possible to use a reference as the value in a standard map container in C++?
If not - why not?

Example declaration:

map<int, SomeStruct&> map_num_to_struct;

Example usage:

...
SomeStruct* some_struct = new SomeStruct();
map_num_to_struct[3] = *some_struct;
map_num_to_struct[3].some_field = 14.3;
cout<<some_struct.some_field;
...

I would expect to see 14.3 printed...

回答1:

No. STL container value types need to be assignable. References are not assignable. (You cannot assign them a different object to reference.)



回答2:

No, it's not. You can use pointers as the value type, though.



回答3:

I don't think so, references are supposed to be treated like constant pointers to a certain element if I remember correctly. But you could just use pointers to the same effect.



回答4:

No, you can't use references but you can use pointers. You seem to be mixing up both in your example. Try:

map<int, SomeStruct *> map_num_to_struct;
SomeStruct* some_struct = new SomeStruct();
map_num_to_struct[3] = some_struct;
map_num_to_struct[3]->some_field = 14.3;
cout<<some_struct->some_field;


回答5:

Value types must be assignable, and references are not.

Anyway you can use a tr1 reference_wrapper.