Why Can't I store references in a `std::map` in C++?

ng5000 picture ng5000 · Oct 9, 2009 · Viewed 32.1k times · Source

I understand that references are not pointers, but an alias to an object. However, I still don't understand what exactly this means to me as a programmer, i.e. what are references under the hood?

I think the best way to understand this would be to understand why it is I can't store a reference in a map.

I know I need to stop thinking of references as syntactic suger over pointers, just not sure how to :/

Answer

Sebastiaan M picture Sebastiaan M · Oct 9, 2009

They way I understand it, references are implemented as pointers under the hood. The reason why you can't store them in a map is purely semantic; you have to initialize a reference when it's created and you can't change it afterward anymore. This doesn't mesh with the way a map works.