Reference to temporary

A

Andriy Shnyr

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?
 
R

Rolf Magnus

Andriy said:
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'.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top