Const reference to a temporary object - Why?

D

Dave Rahardja

Hi all,

Although the following definition is legal:

const int& i = 5;

....and that the lifetime of the temporary variable to which i refers is
identical to i itself, why would anyone want to do this instead of a simple

const int i = 5;

....?

I can see how binding a const reference to a temporary object is necessary
(such as when passing an rvalue to a function expecting a const reference),
but the above usage perplexes me.

-dr
 
V

Victor Bazarov

Dave said:
Although the following definition is legal:

const int& i = 5;

...and that the lifetime of the temporary variable to which i refers
is identical to i itself, why would anyone want to do this instead of
a simple

const int i = 5;

...?

You should ask somebody who did/does that.
I can see how binding a const reference to a temporary object is
necessary (such as when passing an rvalue to a function expecting a
const reference), but the above usage perplexes me.

There is nothing perplexing in that code by itself. It _would_ be
seriously perplexing in a production codebase. I have never seen
anything like that in production code.

V
 
A

Andrej Hristoliubov

I have never seen anything like that in production code.

Dave -

Do listen to Victor, I neither had seen this in production not
Victor's code. And I know Victor for quite some time now (Vitya is it
25 or 30 years in total is the duration of our acquaintance and
bestfriendship?).
 
P

Pete C

Dave -
Do listen to Victor, I neither had seen this in production not
Victor's code. And I know Victor for quite some time now (Vitya is it
25 or 30 years in total is the duration of our acquaintance and
bestfriendship?).

That is great advice. If anyone with your level of expertise in c++ has
experience in IRC, MIME and POP3 protocols I am happy to accept Job
Application for position in the US. Applicants must have skills of a
management of a team of the programmers.
 
D

Dave Rahardja

You should ask somebody who did/does that.

I did, and his reasons (optimization) turned out to be misguided.
There is nothing perplexing in that code by itself. It _would_ be
seriously perplexing in a production codebase. I have never seen
anything like that in production code.

Neither have I, and I prevented one instance from creeping into our codebase
(by talking my colleague out of using it for (false) optimization).

What's perplexing is that such behavior as the lifetime of a temporary bound
to a const reference is defined at all. Stroustrup even gave an example of it
in C++PL (Section 5.5, pg 98 in 3rd ed). Seeing that the C++ language doesn't
seem to support constructs that are not either useful or maintain backward
compatibility, I'm wondering why such behavior is even defined at all.

I'm just trying to figure out the motivation behind the behavior, that's all.

-dr
 
J

Jonathan Mcdougall

Dave said:
I did, and his reasons (optimization) turned out to be misguided.


Neither have I, and I prevented one instance from creeping into our codebase
(by talking my colleague out of using it for (false) optimization).

What's perplexing is that such behavior as the lifetime of a temporary bound
to a const reference is defined at all. Stroustrup even gave an example of it
in C++PL (Section 5.5, pg 98 in 3rd ed). Seeing that the C++ language doesn't
seem to support constructs that are not either useful or maintain backward
compatibility, I'm wondering why such behavior is even defined at all.

I'm just trying to figure out the motivation behind the behavior, that's all.

Consistency.


Jonathan
 
V

Victor Bazarov

Dave said:
Dave said:
Although the following definition is legal:

const int& i = 5;

...and that the lifetime of the temporary variable to which i refers
is identical to i itself, why would anyone want to do this instead
of a simple

const int i = 5;

...?
[..]

I'm just trying to figure out the motivation behind the behavior,
that's all.

I don't understand what special motivation except consistency you
might need. If you think that initialising a const reference by
binding to a temporary (and thus prolonging the life of the object)
is OK when passing to a function or as a member of another object,
then why not stand-alone?

V
 
A

Alf P. Steinbach

* Victor Bazarov:
Dave said:
Dave Rahardja wrote:
Although the following definition is legal:

const int& i = 5;

...and that the lifetime of the temporary variable to which i refers
is identical to i itself, why would anyone want to do this instead
of a simple

const int i = 5;

...?
[..]

I'm just trying to figure out the motivation behind the behavior,
that's all.

I don't understand what special motivation except consistency you
might need. If you think that initialising a const reference by
binding to a temporary (and thus prolonging the life of the object)
is OK when passing to a function or as a member of another object,
then why not stand-alone?

The point is that for a function call, or in an initializer list, and
especially in a function return, the temporary's life is not prolonged.
C++ adds _special_ support for local references to const. And then one
can view binding in function calls / init lists as just a consequence,
but why allow binding rvalues to local references in the first place?
The rules would be just as simple if only binding to arguments was
allowed for rvalues. I think the rules would be _simpler_, and also C++
compilation, and it would, I think, help to detect some obscure bugs.

I've tried to think of optimization scenarios, e.g. an 'extern "C"'
function returning a huge C struct, but no, the feature doesn't seem to
be able to help the compiler.

Perhaps the explanation is the same as (this is what's been stated by
folks Who Should Know) for the non-support of elision of copy
construction for arguments: some committee member(s) had or knew of
code, perhaps some company's zillion line application or perhaps a
popular compiler, that depended on having the language the way it's now
standardized.
 
D

Dave Rahardja

The point is that for a function call, or in an initializer list, and
especially in a function return, the temporary's life is not prolonged.
C++ adds _special_ support for local references to const. And then one
can view binding in function calls / init lists as just a consequence,
but why allow binding rvalues to local references in the first place?
The rules would be just as simple if only binding to arguments was
allowed for rvalues. I think the rules would be _simpler_, and also C++
compilation, and it would, I think, help to detect some obscure bugs.

Right. The special extension of the temporary's lifetime is what got me
scratching my head.

Oh well, it may be one of those things that "just are".

-dr
 
B

bjarne

The rules for references are simply the most general and uniform I
could find. In the cases of arguments and local references, the
temporary lives as long as the reference to which it is bound. One
obvious use is as a shorthand for a complicated expression in a
deeplynested loop. For example:

for (int i = 0; i<xmax; ++i)
for (int j = 0; j< ymax; ++j) {
double& r = a[j];
for (int k = 0; k < zmax; ++k) {
// do something with a[j] and a[j][k]
}
}

This can improve readability as well as run-time performance.


-- Bjarne Stroustrup; http://www.research.att.com/~bs
 
S

STOP

How exactly would the readability and run-time performance be affected
if we used a regular auto?

double r = a[j];

I find the above line more readable - not because it's one char shorter
than the reference-using one but because it raises no questions and
head-scratching. And as far as performace goes I thought modern
compilers could handle the described case just fine. I would really
like to hear your clarification though!

Thanks!
 
A

Alf P. Steinbach

* STOP:
double r = a[j];


You can not assign to the array element via that 'r', so it does not do
the same job as the reference you think it replaces.
 
A

Alf P. Steinbach

* bjarne:
The rules for references are simply the most general and uniform I
could find.

I guess it boils down to the subjectively "simple", then. Thanks for
the explanation.

In the cases of arguments and local references, the
temporary lives as long as the reference to which it is bound. One
obvious use is as a shorthand for a complicated expression in a
deeplynested loop. For example:

for (int i = 0; i<xmax; ++i)
for (int j = 0; j< ymax; ++j) {
double& r = a[j];
for (int k = 0; k < zmax; ++k) {
// do something with a[j] and a[j][k]
}
}

This can improve readability as well as run-time performance.


Yes, but it does not illustrate a case where binding a local reference
to const, to an rvalue, is of any direct practical value -- so the
value of that is presumably only that it provides a simple, general set
of rules?
 
B

bjarne

A simple, general, set of rules is the ideal. As far as possible, the
rules for T& and const T& are the same as are the rules for T& and U&.
However, modify my example a bit

for (int i = 0; i<xmax; ++i)
for (int j = 0; j< ymax; ++j) {
const vector<double>& r = a[j];
for (int k = 0; k < zmax; ++k) {
// do something with a[j] and a[j][k]
}
}

You still have the notational advantage, and we wouldn't want to write

vector<double> r = a[j];

and copy 1000 elements. Obviously, it is also more realistic to have
a[j] a vector than a double (since I proceeded to subscript it :)

-- Bjarne Stroustrup; http://www.research.att.com/~bs
 
S

STOP

You can not assign to the array element via that 'r', so it does not do
the same job as the reference you think it replaces.

Oh, but.. yes, of course - how very silly of me!
I hope *nobody* saw this utterly shameful slip-up :))
...exqueezemoi eurobody
 
A

Alf P. Steinbach

* bjarne:
A simple, general, set of rules is the ideal. As far as possible, the
rules for T& and const T& are the same as are the rules for T& and U&.
However, modify my example a bit

for (int i = 0; i<xmax; ++i)
for (int j = 0; j< ymax; ++j) {
const vector<double>& r = a[j];
for (int k = 0; k < zmax; ++k) {
// do something with a[j] and a[j][k]
}
}

You still have the notational advantage, and we wouldn't want to write

vector<double> r = a[j];

and copy 1000 elements. Obviously, it is also more realistic to have
a[j] a vector than a double (since I proceeded to subscript it :)


Heh... ;-) I didn't even notice that type-o, I guess because that
wasn't what you tried to communicate.

However, the above isn't an example of the temporary lifetime extension,
either.

Somewhere there must be an example of practical usefulness, I'm sure!

On the third hand, I just stumbled over an issue seemingly a consequence
of this general idea of _generating_ a tempory to bind a reference to,
namely that with the current standard the following should not compile,
and indeed does not compile with g++ 3.4.4, nor with Comeau Online
4.3.3, because of that generated temporary requiring copy construction:

#include <memory>

struct E {};

typedef std::auto_ptr<E> EPtr;

EPtr foo() { return EPtr( new E ); }
EPtr bar( EPtr const& ) { return EPtr( new E ); }

int main()
{
bar( foo() ); // Oops! Not allowed by current rules!
}

After a bit of searching I found that this utter silliness, which also
was a stumbling block for Andrei's Mojo, has been adressed by core issue
391, <url:
http://www2.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#391>, and
"voted into WP" (that's C++0x, isn't it?), and that's nice.

But that doesn't help us until C++0x, which is -- when?


Cheers,

- Alf
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top