Hello Experts!
I'm reading in a book about C++ and the book says common errors is
"A function should not return a constant references to its parameter passed
by constant references"
Why?
Here I have written a method that has exactly this which is the parameter is
passed by constant references and I return constant references what is it
that can cause common error by writng in this way.
main()
{
int tal = 9;
Test t;
t.foo(tal);
}
class Test
{
const int& foo(const int& i)
{
return i;
}
};
Many thanks
//Tony 6 1951
Tony Johansson wrote: Hello Experts!
I'm reading in a book about C++ and the book says common errors is "A function should not return a constant references to its parameter passed by constant references" Why?
const int& f(const int& i)
{
return i;
}
void bogus()
{
const int& j = f(int());
// j is now dangling
}
The danger is that if you call f with a temporary, as the code above
does, it returns a reference to that temporary, which becomes invalid
when the temporary goes away. That danger doesn't mean you shouldn't do
it, but that if you do, you have to be sure of how you use it.
--
Pete Becker
Dinkumware, Ltd. ( http://www.dinkumware.com)
Tony Johansson wrote: I'm reading in a book about C++
Could you please cite the book?
and the book says that a common error is
"A function should not return a constant references to its parameter passed by constant references"
Can you please cite the passage which contains the above quote?
Can you tell us the name of the author?
Why?
Here I have written a method that has exactly this [where] the parameter is passed by constant reference and I return constant a reference. What is it that can cause a common error by writng in this way?
cat main.cc
#include <iostream>
class Test {
public:
const int& foo(const int& i) const {
return i;
}
};
int main(int argc, char* argv[]) {
int tal = 9;
Test t;
std::cout << "t.foo(" << tal << ") = "
<< t.foo(tal) << std::endl;
return 0;
}
g++ -Wall -ansi -pedantic -O2 -o main main.cc ./main
t.foo(9) = 9
It works just fine for me.
My guess is that you have misread the author
and now you are confused.
* Tony Johansson: I'm reading in a book about C++ and the book says common errors is "A function should not return a constant references to its parameter passed by constant references" Why?
Because the ref-to-const parameter means you can (easily) pass in a temporary,
e.g. the literal number 42, and that temporary will not exist any longer when
evaluation of the expression that the function call occurs in is finished.
Actually it may be destroyed even earlier, as soon as the function returns,
because §5.2.2/4 says "The lifetime of a parameter ends when the function in
which it is defined returns". However, §12.2/5 says "A temporary bound to a
reference parameter in a function call persists until the completion of the
full expression containing the call." Take your pick.
Thus, for a temporary as argument, the function result can only be safely
used inside the expression the function call occurs in. And even there it
might not be safe to use it. Depending on how you read the Holy Standard.
Personally I think §12.2/5 is the most specific and therefore applies, and a
fair amount of code would, I believe, be broken if §5.2.2/4 is the "winner".
Here I have written a method that has exactly this which is the parameter is passed by constant references and I return constant references what is it that can cause common error by writng in this way.
main()
'main' must have 'int' result type; this should not compile
(unfortunately a certain compiler from a large company allows it).
{ int tal = 9; Test t;
Class 'Test' is not known at this point.
This should not compile.
I don't know any compiler that accepts it.
t.foo(tal);
Any real test would have to use the result.
However, that only tells you what a specific compiler does.
It doesn't tell you whether it's behavior mandated by the standard.
}
class Test { const int& foo(const int& i) { return i; } };
Hth.
--
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?
On Wed, 06 Apr 2005 20:59:13 +0000, Tony Johansson wrote: Hello Experts!
I'm reading in a book about C++ and the book says common errors is "A function should not return a constant references to its parameter passed by constant references" Why? Here I have written a method that has exactly this which is the parameter is passed by constant references and I return constant references what is it that can cause common error by writng in this way.
main() { int tal = 9; Test t; t.foo(tal); }
class Test { const int& foo(const int& i) { return i; } };
Many thanks //Tony
You can bind a temporary to a const reference. What if you did:
t.foo(9);
Here's another example:
#include <iostream>
class A
{
public:
A() { i = 3; }
~A() { i = 5; }
int GetI() const { return i; }
private:
int i;
};
const A& foo(const A& a)
{
return a;
}
int main()
{
const A& a = foo(A());
std::cout << a.GetI() << std::endl;
}
gcc gives "5" (though I suspect we've entered into undefined behavior at
this point).
- Jay
Alf P. Steinbach wrote: * Tony Johansson: I'm reading in a book about C++ and the book says common errors is "A function should not return a constant references to its
parameter passed by constant references" Why? Because the ref-to-const parameter means you can (easily) pass in a
temporary, e.g. the literal number 42, and that temporary will not exist any
longer when evaluation of the expression that the function call occurs in is
finished. Actually it may be destroyed even earlier, as soon as the function
returns, because §5.2.2/4 says "The lifetime of a parameter ends when the
function in which it is defined returns".
No, 5.2.2/4 talks about the reference parameter and not the object
to which the reference is bound. Compare:
void foo() {
int i = 0;
{
int const& ri = i;
}
}
The lifetime of ri ends at the first }, but the lifetime of i ends
at the second }.
The fact that the reference is bound to a temporary doesn't matter
here. The only case in which a temporary is destroyed due to the
end of the lifetime of a reference is when the temporary would have
been destoyed earlier in the absence of the reference. I.e.
references can extend lifetimes but not shorten them.
Regards,
Michiel Salters
* msalters: Alf P. Steinbach wrote: * Tony Johansson: I'm reading in a book about C++ and the book says common errors is "A function should not return a constant references to its parameter passed by constant references" Why?
Because the ref-to-const parameter means you can (easily) pass in a temporary, e.g. the literal number 42, and that temporary will not exist any longer when evaluation of the expression that the function call occurs in is finished. Actually it may be destroyed even earlier, as soon as the function returns, because =A75.2.2/4 says "The lifetime of a parameter ends when the function in which it is defined returns".
No, 5.2.2/4 talks about the reference parameter and not the object to which the reference is bound. Compare:
void foo() { int i =3D 0; { int const& ri =3D i; } } The lifetime of ri ends at the first }, but the lifetime of i ends at the second }.
On reflection I think you're right.
Which means my tentative conclusion in the posting the above was a follow-up
to was right, for the wrong reasons.
However, I also think the standard is unclear & even misleading here.
--
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? This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Aravind |
last post by:
I would like to know in what manner dangling pointers affect the
security of a application developed using C++.What are the loopholes
that are created by dangling pointers and how they could be exploited
by hackers?.
Aravind
|
by: Matthias Kaeppler |
last post by:
Hi,
I have a question regarding references, and their chance to "dangle" (if
that's possible at all):
Say I have a collection ob objects, and I take a reference to one of
them. Now I sort this collection, or invoke whatever action it takes to
copy around the elements in the collection.
What happens to the reference?
|
by: __PPS__ |
last post by:
Hello everybody
in a quiz I had a question about dangling pointer:
"What a dangling pointer is and the danger of using it"
My answer was:
"dangling pointer is a pointer that points to some area of ram that's
not reserved by the program. Accessing memory through such pointer is
likely to result in core dump (memory access violation)"
|
by: Richard |
last post by:
My experience has always been that you're SOL when trying to safely
detect and stop references to dangling memory (non-null pointers to
free'ed blocks) at runtime (C99, Linux).
Maybe somebody clever has worked this out, though?
(Apologies to those who find the question off topic for CUP or CLC)
|
by: sekhar_ps |
last post by:
if we store some value at the place in memory which void pointer references then we increment void pointer this leads to dangling pointer?can any one explain whats the reasons for dangling pointer
| |
by: Belebele |
last post by:
Suppose that I have a method that returns references to "elements" in
an iterator, and a method to advance the iterator:
class Element { /* ... */ };
class Iterator {
public:
Element& operator*() const;
Iterator& operator++();
|
by: sridhard2406 |
last post by:
Hi All,
I have a doubt on undrestanding Dangling pointers.Below I mentioned sample code. please let me know, my view on Dangling pointers is correct or not?
main( )
{
char *a,*b,*c;
a = (char *)malloc(40);
b = a;
c = b;
free(a);
|
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...
|
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,...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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...
| |
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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...
| |