|
-
May 9th, 2004, 02:22 PM
#1
const references? I'm confused.
Hey again,
I've just read something very confusing in Stroustrups book about so called const references after running into this "problem":
Consider a class C like this:
Code:
class C
{
std::string str;
public:
C() { str = "original"; }
const std::string & GetStr() const { return str; }
};
and a program, maybe like this:
Code:
C c;
std::string & ref = c.GetStr();
ref = "changed!";
cout << c.GetStr() << endl;
The output is "original". Frankly I would have expected that ref would change the value of C's data member but it doesn't. And it's not because str is const, because it isn't!
The passage about const references in Stroustrup's is somewhat vague... From what I've understood, a reference to a temporary object is returned instead of a reference to the data member itself, therefore ref = "changed" will not change the member but the temp var. However, when I leave the method's scope that temp var would be removed from the stack, so how can I still have a valid reference to it?!
Can someone explain this problem a little more in detail?
- Matthias
"C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off." - Bjarne Stroustrup
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|