Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Reference to temporary

Reply
Thread Tools

Reference to temporary

 
 
Andriy Shnyr
Guest
Posts: n/a
 
      02-25-2004
Hallo!
I have the following example:
class Test{
public:
Test(int const level): _level(level), _next(0){}
void add_next(Test* const next){
_next = next;
}
Test* const& get(int const level){
if(_next != 0 && _next->_level >= level)
return _next->get(level);
else
return this;
}
void print(){
cout << _level<< endl;
}
private:
Test* _next;
int const _level;
};
Compiling this example with gcc 3.2 results in the following warning
"Returning reference to temporary"
line "return this"
Ok, I understand may be it is enough to return "T* const" not a
reference, but still I do not understand the reason
Is is safe to return such a reference?
 
Reply With Quote
 
 
 
 
Rolf Magnus
Guest
Posts: n/a
 
      02-25-2004
Andriy Shnyr wrote:

> Hallo!
> I have the following example:
> class Test{
> public:
> Test(int const level): _level(level), _next(0){}
> void add_next(Test* const next){
> _next = next;
> }
> Test* const& get(int const level){
> if(_next != 0 && _next->_level >= level)
> return _next->get(level);
> else
> return this;
> }
> void print(){
> cout << _level<< endl;
> }
> private:
> Test* _next;
> int const _level;
> };
> Compiling this example with gcc 3.2 results in the following warning
> "Returning reference to temporary"
> line "return this"
> Ok, I understand may be it is enough to return "T* const" not a
> reference,


Actually, it would even be enough to return a T*, without the const.

> but still I do not understand the reason
> Is is safe to return such a reference?


'this' is a pointer to the object that the function is currently working
on. It is usually a hidden parameter to the function, and so it is
local to the function and doesn't exist after returning from it.
Therefore, I think it's not safe to return a reference to 'this'.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
anonymous array of strings // ("taking address of temporary"- how long is temporary valid?) anon.asdf@gmail.com C++ 7 02-12-2008 10:58 AM
A reference to non-const to be bound to a temporary object John Ky C++ 9 02-23-2004 12:53 AM
Reference to temporary Dave C++ 11 11-07-2003 10:38 AM
The temporary vs non-const reference love story =?ISO-8859-1?Q?Ney_Andr=E9_de_Mello_Zunion?= C++ 13 11-06-2003 02:52 PM
iterator / returning reference to local temporary Alexander Stippler C++ 2 07-04-2003 04:40 PM



Advertisments