473,386 Members | 1,720 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Const reference to a temporary object - Why?

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
Oct 29 '05 #1
15 6279
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;

...?
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
Oct 29 '05 #2
> I have never seen anything like that in production code.
V


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?).

Oct 29 '05 #3
> 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.

Oct 29 '05 #4
On Fri, 28 Oct 2005 23:24:40 -0400, "Victor Bazarov" <v.********@comAcast.net>
wrote:
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;

...?


You should ask somebody who did/does that.


I did, and his reasons (optimization) turned out to be misguided.
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.


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
Oct 29 '05 #5
Dave Rahardja wrote:
On Fri, 28 Oct 2005 23:24:40 -0400, "Victor Bazarov" <v.********@comAcast.net>
wrote:
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;

...?


You should ask somebody who did/does that.


I did, and his reasons (optimization) turned out to be misguided.
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.


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

Oct 30 '05 #6
Dave Rahardja wrote:
On Fri, 28 Oct 2005 23:24:40 -0400, "Victor Bazarov"
<v.********@comAcast.net> wrote:
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?

V
Oct 30 '05 #7
* Victor Bazarov:
Dave Rahardja wrote:
On Fri, 28 Oct 2005 23:24:40 -0400, "Victor Bazarov"
<v.********@comAcast.net> wrote:
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.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Oct 30 '05 #8
On Sun, 30 Oct 2005 02:12:52 GMT, al***@start.no (Alf P. Steinbach) wrote:
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
Oct 30 '05 #9
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[i][j];
for (int k = 0; k < zmax; ++k) {
// do something with a[i][j] and a[i][j][k]
}
}

This can improve readability as well as run-time performance.
-- Bjarne Stroustrup; http://www.research.att.com/~bs

Oct 30 '05 #10
How exactly would the readability and run-time performance be affected
if we used a regular auto?

double r = a[i][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!

Oct 30 '05 #11
* STOP:

double r = a[i][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: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Oct 30 '05 #12
* 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[i][j];
for (int k = 0; k < zmax; ++k) {
// do something with a[i][j] and a[i][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?

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Oct 30 '05 #13
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[i][j];
for (int k = 0; k < zmax; ++k) {
// do something with a[i][j] and a[i][j][k]
}
}

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

vector<double> r = a[i][j];

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

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

Oct 31 '05 #14
>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

Oct 31 '05 #15
* 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[i][j];
for (int k = 0; k < zmax; ++k) {
// do something with a[i][j] and a[i][j][k]
}
}

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

vector<double> r = a[i][j];

and copy 1000 elements. Obviously, it is also more realistic to have
a[i][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

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 3 '05 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Bolin | last post by:
Hi all, A question about smart pointers of constant objects. The problem is to convert from Ptr<T> to Ptr<const T>. I have look up and seen some answers to this question, but I guess I am too...
19
by: Christian Engström | last post by:
If you have a function that returns something by value, the gcc compiler (version 3.2.3 on Windows XP with MinGW) converts the returned value from the type you specify in the code, to the const...
5
by: klaus triendl | last post by:
hi, recently i discovered a memory leak in our code; after some investigation i could reduce it to the following problem: return objects of functions are handled as temporary objects, hence...
5
by: Dave | last post by:
Hello all, I've been wondering... Why is it that a reference may be bound only to a const object? If a reference were bound to a non-const object and that object were modified, what harm could...
8
by: bipod.rafique | last post by:
Hello All, I need your help in understanding something. I have a simple class class test{ };
10
by: ATASLO | last post by:
In the following example, section #3 fails under VC98, VC2003, VC2005 Express Beta (Aug 2004) and g++ 3.3.2. Is this just a pitfall of the C++ specification? Why don't any of the above compilers...
10
by: JurgenvonOerthel | last post by:
Consider the classes Base, Derived1 and Derived2. Both Derived1 and Derived2 derive publicly from Base. Given a 'const Base &input' I want to initialize a 'const Derived1 &output'. If the...
3
by: rwf_20 | last post by:
Hi, I'm looking at the differences between: const NonTrivialObject& obj = functionThatReturnsANonTrivialObjectByValue(); and: const NonTrivialObject obj =
5
by: George2 | last post by:
Hello everyone, This is my understanding of non-const reference, const reference and their relationships with lvalue/rvalue. Please help to review whether it is correct and feel free to...
3
by: George2 | last post by:
Hello everyone, 1. Returning non-const reference to function local object is not correct. But is it correct to return const reference to function local object? 2. If in (1), it is correct...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.