🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c++
Article #422

Re: const reference

#422
From: Andrew Koenig
Date: Sat, 25 Aug 1990 15:10
48 lines
2079 bytes
In article <6285@darkstar.ucsc.edu>, daniel@cis.ucsc.edu (Daniel Edelson) writes:

> Is there a concensus on what a const reference means?

If you truly mean a const reference, such as

	int x;
	int &const y = x;

then I've never seen such a thing.  I suppose it would have to mean
a reference that you're not allowed to change, even though you can
change the thing to which it refers.  But that's true of all references,
so `const' here doesn't add anything.

If, on the other hand, you mean a reference to const:

	const int& z = x;

then that does carry a useful semantic meaning.  I've said here that
z is an alias to x, but I promise that I will not use z to change x.

The most common use of such things is as formal paramters to functions
that do not wish to incur the overhead of copying their argument.
For example:

	complex operator+(const complex& x, const complex& y)
	{
		return complex(x.re() + y.re(), x.im() + y.im() );
	}

This function uses references to constants as a way to avoid copying the
arguments, which would presumably be slower.

There is one other semantic detail that is important: a reference to constant
may be bound to any expression, while an ordinary reference may be bound
only to an lvalue:

	int& x = 3;		// illegal
	const int& x = 3;	// OK

You may be surprised to see that the first example is illegal.
Perhaps a better word is `deprecated:' the manual says it's illegal
but many compilers still allow it.  The point is to prohibit stuff like this:

	cin >> (x + y);		// ???
-- 
				--Andrew Koenig
				  ark@europa.att.com
Technical Details
Message-ID: <11234@alice.UUCP>
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!samsung!zaphod.mps.ohio-state.edu!mips!pacbell.com!pacbell!att!dptg!ulysses!andante!alice!ark
References: <6285@darkstar.ucsc.edu>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!samsung!zaphod.mps.ohio-state.edu!mips!pacbell.com!pacbell!att!dptg!ulysses!andante!alice!ark
From: ark@alice.UUCP (Andrew Koenig)
Newsgroups: comp.std.c++
Subject: Re: const reference
Keywords: Trying to pick a fight
Message-ID: <11234@alice.UUCP>
Date: 25 Aug 90 15:10:52 GMT
References: <6285@darkstar.ucsc.edu>
Organization: AT&T Bell Laboratories, Liberty Corner NJ
Lines: 48