On Tue, 2015-07-07, Alf P. Steinbach wrote:
> On 07-Jul-15 5:02 PM,
peps...@gmail.com wrote:
>> Textbooks often say things like "int& x = y; simply means that x is an
>> alias for y."
>>
>> However, this is ambiguous (to me). Take the following case.
>> std::vector<int> vec; /* ..... */ int index = 5; int& ref = vec[index];
>>
>> Is ref an alias for vec[5] or for vec[index]? In other words if index
>> changes from 5 to 6, does ref now refer to vec[6]? Or does ref always refer
>> to vec[5]?
>
> Good question.
>
> In C++ a reference refers to the result of the evaluation of the
> initializer expression. But (as I recall) due to a sloppy formulation of
> the specification of an early version of the Algol language, [...]
Etc. In C++ -- (and all real languages. except pure pre-processor
languages like cpp[0]) -- expressions are evaluated where they are, in
their current context. So "index" is 5, and "ref" is a reference to
vec[5], whatever that is at that point in time. Like any other
reference into a std::vector, it's vulnerable to invalidation, though.
For example, if you add enough elements to "vec" to force it to
reallocate itself, "ref" will point to something crazy and
unpredictable. If you don't it's just a sane reference to vec[5].
/Jorgen
[0] cpp and make are the only remaining languages with this property
that I can think of. Maybe m4 as well. Too bad that one of them
is embedded into every C and C++ compiler ...
--
// Jorgen Grahn <grahn@ Oo o. . .
\X/
snipabacken.se> O o .