473,788 Members | 2,726 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 6338
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.********@com Acast.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.********@com Acast.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.********@com Acast.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.********@com Acast.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

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

Similar topics

5
5064
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 stupid to understand and make them work. E.g. I have read that boost's smart pointers are able to do this convertion, but the following code doesn't compile (VC++6.0):
19
2808
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 version of that type. Is this a bug that is specific to gcc, or is it a flaw in the language specification that gcc diligently implements? For example, the below program produces the output Constant Mutable
5
3755
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 their dtor is called immediately and not at the end of the function. to be able to use return objects (to avoid copying) i often assign them to a const reference. now, casting a const return object from a function to a non-const reference to this...
5
1538
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 result? A temporary is just as real of an object as any other. It lacks a name, but that doesn't make it less real. Class (no pun intended) warfare seems to be alive and well! Thanks, Dave
8
2751
by: bipod.rafique | last post by:
Hello All, I need your help in understanding something. I have a simple class class test{ };
10
1540
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 at least flag this as a warning as they would when say trying to return a const & to a local? In Section #2, the const B& Bref is initialized and bound to the temporary returned from GetSettings(). That is the temporary B exists until Bref goes...
10
3449
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 dynamic type of 'input' is Derived1, then 'output' should become a reference to 'input'. Otherwise 'output' should become a reference to the (temporary) result of the member function 'input.to_der1()' which returns a Derived1 object by value.
3
1816
by: rwf_20 | last post by:
Hi, I'm looking at the differences between: const NonTrivialObject& obj = functionThatReturnsANonTrivialObjectByValue(); and: const NonTrivialObject obj =
5
449
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 correct me. Thanks. 1. A const reference can be binded to a rvalue, for example, a temporary object. And the "life" of the temporary object is guaranteed to be extended and we can safely operate through the const-reference.
3
5811
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 to return const reference to function local object, the process is a new temporary object is created (based on the function local object) and the const reference is binded to the
0
9498
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10366
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10112
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9969
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5399
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3675
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.