473,385 Members | 1,930 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,385 software developers and data experts.

non-const reference and const reference

200 100+
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.

2. A non-const reference can not binded to a rvalue, I think the reason is rvalue is not addressable? And we can not change the rvalue through its reference? Are there any other reasons? I am not quite sure whether my understanding is fully correct. Since there are some non-modifiable lvalues (so we do not always need to modify values through its reference). I am still studying what is the reason in essence in compiler why a non-const reference can not be binded to a rvalue.

3. Both const and non-const reference can be binded to a lvalue.


thanks in advance,
George
Dec 15 '07 #1
17 3416
weaknessforcats
9,208 Expert Mod 8TB
I'm not sure what you are talking about:
Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.       int data = 25;
  4.       const int& rcdata = data;
  5.       int& rdata = data;
  6.  
  7.       data = rdata;           //non-const reference as rvalue
  8.       data = rcdata;         //const reference as rvalue
  9. }
  10.  
Here a variable is assgined to itself using references as rvalues.

Also a reference does not extend the life of a variable. If you return a reference of any kind to a local variable in a function, the reference is garbage when the local variable of the function is deleted. The sad thing is that the compiler may no delete the local variable immeidiately so your code appears to work- maybe.

Try to not make up rules around references. A reference is just an alternate name for a variable. If the reference is const, then the variable is considerend const when you use the reference (whether is variable is really const is irrelevant). If the reference is not const then the variable is considered not const. If the variable is really const and the referecne is not const, then you will get a compiler error trying to make a non-const reference to a const variable. If the compiler allows it, you could use the non-const referecne to chnage the valus of the const variable. That's a big no-no.
Dec 16 '07 #2
George2
200 100+
Thanks weaknessforcats,


Your reply is great! But I can not see your direct answer to my original 3 questons. :-)

I'm not sure what you are talking about:
Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.       int data = 25;
  4.       const int& rcdata = data;
  5.       int& rdata = data;
  6.  
  7.       data = rdata;           //non-const reference as rvalue
  8.       data = rcdata;         //const reference as rvalue
  9. }
  10.  
Here a variable is assgined to itself using references as rvalues.

Also a reference does not extend the life of a variable. If you return a reference of any kind to a local variable in a function, the reference is garbage when the local variable of the function is deleted. The sad thing is that the compiler may no delete the local variable immeidiately so your code appears to work- maybe.

Try to not make up rules around references. A reference is just an alternate name for a variable. If the reference is const, then the variable is considerend const when you use the reference (whether is variable is really const is irrelevant). If the reference is not const then the variable is considered not const. If the variable is really const and the referecne is not const, then you will get a compiler error trying to make a non-const reference to a const variable. If the compiler allows it, you could use the non-const referecne to chnage the valus of the const variable. That's a big no-no.

regards,
George
Dec 17 '07 #3
weaknessforcats
9,208 Expert Mod 8TB
The code sample isn't enough?? What else would you like me to say?
Dec 17 '07 #4
RRick
463 Expert 256MB
#1 sounds like something that might be supported in Java, but not in C++. Read what W4cats said about this topic.

As for the other two questions, I'm with W4cats, I'm not sure what your are asking. A couple of examples (and descriptions) for each question would help.
Dec 17 '07 #5
George2
200 100+
Thanks weaknessforcats,


My question is answered.

The code sample isn't enough?? What else would you like me to say?

regards,
George
Dec 19 '07 #6
George2
200 100+
Thanks RRick,


#1 sounds like something that might be supported in Java, but not in C++. Read what W4cats said about this topic.

As for the other two questions, I'm with W4cats, I'm not sure what your are asking. A couple of examples (and descriptions) for each question would help.

My question is answered.


regards,
George
Dec 19 '07 #7
qatal
1
#1 sounds like something that might be supported in Java, but not in C++. Read what W4cats said about this topic.

As for the other two questions, I'm with W4cats, I'm not sure what your are asking. A couple of examples (and descriptions) for each question would help.
RRick: #1 (reference to const extends the lifetime of a temp to the lifetime of the reference) is explicitly provided for by the C++ standard.
Jan 20 '08 #8
weaknessforcats
9,208 Expert Mod 8TB
RRick: #1 (reference to const extends the lifetime of a temp to the lifetime of the reference) is explicitly provided for by the C++ standard.
It does not.

A reference is an alias for the original variable. The variable will continue to exist as long as its scope permits. The reference does not change that. The lifetime of the temp is an oxymoron since there is no temp variable. The referecne name goes out of scope at the end of the function.
Jan 21 '08 #9
George2
200 100+
I do not agree with you, weaknessforcats! I think he means const reference. :-)

Please refer to Bjarne's book, section 5.5 there is sample which verifies the life of temporary object is prolonged until the life of the const reference.

It does not.

A reference is an alias for the original variable. The variable will continue to exist as long as its scope permits. The reference does not change that. The lifetime of the temp is an oxymoron since there is no temp variable. The referecne name goes out of scope at the end of the function.

regards,
George
Jan 22 '08 #10
weaknessforcats
9,208 Expert Mod 8TB
Read that carefully. Bjarne is a lawyer.

A const reference often requires the creation of a compiler-created temporary object. It is guaranteed that this temprary will exist as long as the reference exists.

This does not mean that if you return a reference to a local variable that the life of the local variable is extended. You will get the same indeterminate behavior as if you returned the address of a local variable and tried to use it.
Jan 22 '08 #11
RRick
463 Expert 256MB
We need to be careful of the terms we use. I think the key term here is "temporary variable". Returning a reference to a local variable does not fail under that category.

The original post talked about extending the life a variable, but it did not limit all the cases to just a temporary variable. This post sounds like we are mixing the two types (temporary and local) together and they can't be compared this way in terms of a reference.
Jan 22 '08 #12
George2
200 100+
You are correct, weaknessforcats!


1.
Sorry I am talking about other things in previous post. I agree with you know. And I think if we return const reference to the local variable, it should be ok, right?

2.

This will result in creation of a temporary object and return const reference to the temporary obejct, right?

Read that carefully. Bjarne is a lawyer.

A const reference often requires the creation of a compiler-created temporary object. It is guaranteed that this temprary will exist as long as the reference exists.

This does not mean that if you return a reference to a local variable that the life of the local variable is extended. You will get the same indeterminate behavior as if you returned the address of a local variable and tried to use it.

regards,
George
Jan 23 '08 #13
George2
200 100+
Thanks RRick,


I agree with you. I think the previous confusion is not temporary object, but function local object in weaknessforcats's post #9.

We need to be careful of the terms we use. I think the key term here is "temporary variable". Returning a reference to a local variable does not fail under that category.

The original post talked about extending the life a variable, but it did not limit all the cases to just a temporary variable. This post sounds like we are mixing the two types (temporary and local) together and they can't be compared this way in terms of a reference.

regards,
George
Jan 23 '08 #14
micah4
2
Also a reference does not extend the life of a variable. If you return a reference of any kind to a local variable in a function, the reference is garbage when the local variable of the function is deleted. The sad thing is that the compiler may no delete the local variable immeidiately so your code appears to work- maybe.
Do you really teach C++? I'm scared for your students. A const reference extends the life of a temporary from the statement which created the temporary to the scope of the const reference. This is the case e.g., when a reference is held to a temporary which has been returned from a function. You are correct that it does not extend the life of the object if you try to return it outside the function which declared the const reference- but this is clear from Stroustroup, because the const reference which held the temporary goes out of scope when the function exits.

e.g.,

Expand|Select|Wrap|Line Numbers
  1. struct Point
  2. {
  3.    int x;
  4.    int y;
  5.    Point( int x_, int y_ ) : x(x_),y(y_){}
  6.  
  7. Point
  8. makeMyPoint()
  9. {
  10.    return Point( 3, 4 );
  11. }
  12.  
  13. void
  14. someFunction()
  15. {
  16.   // statement 1
  17.    const Point& p = makeMyPoint();
  18.  
  19.    // statement 2
  20.    int distanceFromOrigin = 
  21.       sqrt( (p.x*p.x) + (p.y*p.y) );
  22. }
  23.  
In this case the temporary "Point" object returned by the function "makeMyPoint()" would usually cease to exist at the end of statement 1. But, when a const reference is held that temporary continues to exist as long as the scope of _that_ const reference exists. In this case, the temporary remains until "someFunction()" returns because the const Point& "p" remains in scope until "someFunction()" returns.


Try to not make up rules around references.
Normally I don't mind much people being wrong alone, nor do I too much mind this kind of arrogance- as long as you're right. But being both wrong and arrogant together is a bad combination.
Jan 23 '08 #15
weaknessforcats
9,208 Expert Mod 8TB
Do you really teach C++? I'm scared for your students. A const reference extends the life of a temporary from the statement which created the temporary to the scope of the const reference.
I do. And your example is what I am talking about:
Point makeMyPoint()
{
return Point( 3, 4 );
}

void
someFunction()
{
// statement 1
const Point& p = makeMyPoint();
The temprary returned by makeMyPoint will exist as long as the referecne does. Your example is off the point.

This will not work:
Expand|Select|Wrap|Line Numbers
  1. Point& makeMyPoint()
  2. {
  3.    Point obj(3,4);
  4.    return obj;}
  5.  
  6. void
  7. someFunction()
  8. {
  9.   // statement 1
  10.    const Point& p = makeMyPoint();
  11.  
That is, returning a reference to a local variable does not extend the scope of the local variable.

Go back and read my Post #11 again.
Jan 23 '08 #16
George2
200 100+
Thanks micah4,


All of your reply is great! And I agree. :-)

Below you mentioned, what means "if you try to return it outside the function which declared the const reference"? I can not understand the scenario you mean, could you show more description or show some pseudo code please?

You are correct that it does not extend the life of the object if you try to return it outside the function which declared the const reference

regards,
George
Jan 25 '08 #17
George2
200 100+
I agree, weaknessforcats.


We are talking about two things at this topic. :-)

I do. And your example is what I am talking about:


The temprary returned by makeMyPoint will exist as long as the referecne does. Your example is off the point.

This will not work:
Expand|Select|Wrap|Line Numbers
  1. Point& makeMyPoint()
  2. {
  3.    Point obj(3,4);
  4.    return obj;}
  5.  
  6. void
  7. someFunction()
  8. {
  9.   // statement 1
  10.    const Point& p = makeMyPoint();
  11.  
That is, returning a reference to a local variable does not extend the scope of the local variable.

Go back and read my Post #11 again.

regards,
George
Jan 25 '08 #18

Sign in to post your reply or Sign up for a free account.

Similar topics

12
by: lothar | last post by:
re: 4.2.1 Regular Expression Syntax http://docs.python.org/lib/re-syntax.html *?, +?, ?? Adding "?" after the qualifier makes it perform the match in non-greedy or minimal fashion; as few...
3
by: Mario | last post by:
Hello, I couldn't find a solution to the following problem (tried google and dejanews), maybe I'm using the wrong keywords? Is there a way to open a file (a linux fifo pipe actually) in...
25
by: Yves Glodt | last post by:
Hello, if I do this: for row in sqlsth: ________pkcolumns.append(row.strip()) ________etc without a prior:
32
by: Adrian Herscu | last post by:
Hi all, In which circumstances it is appropriate to declare methods as non-virtual? Thanx, Adrian.
22
by: Steve - DND | last post by:
We're currently doing some tests to determine the performance of static vs non-static functions, and we're coming up with some odd(in our opinion) results. We used a very simple setup. One class...
2
by: Ian825 | last post by:
I need help writing a function for a program that is based upon the various operations of a matrix and I keep getting a "non-aggregate type" error. My guess is that I need to dereference my...
0
by: amitvps | last post by:
Secure Socket Layer is very important and useful for any web application but it brings some problems too with itself. Handling navigation between secure and non-secure pages is one of the cumbersome...
399
by: =?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?= | last post by:
PEP 1 specifies that PEP authors need to collect feedback from the community. As the author of PEP 3131, I'd like to encourage comments to the PEP included below, either here (comp.lang.python), or...
9
by: Francois Grieu | last post by:
When running the following code under MinGW, I get realloc(p,0) returned NULL Is that a non-conformance? TIA, Francois Grieu #include <stdio.h> #include <stdlib.h>
12
by: puzzlecracker | last post by:
is it even possible or/and there is a better alternative to accept input in a nonblocking manner?
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
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...

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.