Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 :/

like image 277
ng5000 Avatar asked Oct 09 '09 11:10

ng5000


People also ask

Can you use references in C?

No, it doesn't. It has pointers, but they're not quite the same thing. For more details about the differences between pointers and references, see this SO question.

How are values stored in map C++?

Maps are associative containers that store elements in a combination of key values and mapped values that follow a specific order. No two mapped values can have the same key values. In C++, maps store the key values in ascending order by default.

How are references stored in C++?

Reference is one type of variable stored on stack because of there is need to perform operation on them where object stored on heap. In c++ references are stored in stack surely.


1 Answers

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.

like image 146
Sebastiaan M Avatar answered Oct 06 '22 00:10

Sebastiaan M