Alex Rivera | Logout

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

Asked 2009-10-09T11:15:02.210
64

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

Edit
Report

2 Answers

10

The important difference apart from the syntactic sugar is that references cannot be changed to refer to another object than the one they were initialized with. This is why they cannot be stored in maps or other containers, because containers need to be able to modify the element type they contain.

As an illustration of this:

A anObject, anotherObject;
A *pointerToA=&anObject;
A &referenceToA=anObject;

// We can change pointerToA so that it points to a different object
pointerToA=&anotherObject;

// But it is not possible to change what referenceToA points to.
// The following code might look as if it does this... but in fact,
// it assigns anotherObject to whatever referenceToA is referring to.
referenceToA=anotherObject;
// Has the same effect as
// anObject=anotherObject;
answered 2009-10-09T11:20:44.813
0

This post explains how pointers are implemented under the hood - http://www.codeproject.com/KB/cpp/References_in_c__.aspx, which also supports sebastians answer.

answered 2011-09-13T04:24:55.523

Your Answer