[LC++]Why map<string, string&> not acceptable?

Jack Lloyd lloyd at acm.jhu.edu
Mon Apr 8 09:03:05 UTC 2002


On Thu, 4 Apr 2002, Shaul Karl wrote:

> Attached a short program and a longer compilation output.
> If I understand it correctly then the type
>
>     map<string, string&>
>
> is not acceptable.

That's correct.

>
> But why?
> In particular, in what circumstances will references to other classes
> instead of string& be accepted?

I don't believe that's possible at all, because in C++, a reference must be
initialized on creation. For example, this doesn't work:

int foo = 5;
int& ref;
ref = foo;

You have to initalize it, for example:

int foo = 5;
int& ref = foo;

map<string, string*> will get you most of what you want, though map<string,
string> seems easier, unless the pointed-to strings are huge and often the
same, so you want to implement sharing (though with the copy-on-write
semantics used by strings, even map<string, string> should be efficient
enough).

-Jack





More information about the tuxCPProgramming mailing list