473,800 Members | 2,495 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
15 6341
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.htm l#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
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
3757
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
2752
by: bipod.rafique | last post by:
Hello All, I need your help in understanding something. I have a simple class class test{ };
10
1542
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
3450
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
9690
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10504
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...
0
10033
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
6811
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
5469
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...
0
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4149
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2945
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.