Initializing a non-const reference with non-lvalue



 DEVELOP > c-Plus-Plus > Initializing a non-const reference with non-lvalue

LINK TO THIS PAGE  


rating :  0   |  0


  Page 1 of 1

1

 
Topic: DEVELOP > c-Plus-Plus
User: "Andrew Ward"
Date: 19 Jul 2005 12:51:49 AM
Object: Initializing a non-const reference with non-lvalue
The following program compiles and runs fine on my compiler (vc7.1):
#include <memory>
using namespace std;
class X {};
auto_ptr<X> foo()
{
return auto_ptr<X>(new X());
}
int main()
{
auto_ptr<X> x;
x = foo();
}
However running it through lint I get the following error:
x = foo();
main.cpp(15) : Error 1058: Initializing a non-const reference
'std::auto_ptr<X>
&' with a non-lvalue
As this is a lint error, not a warning, I would not have thought it
would compile, should it have? Could someone explain the error to me?
Thanks.
.

User: "Zorro"

Title: Re: Initializing a non-const reference with non-lvalue 19 Jul 2005 01:53:13 AM
Lint is correct. Look at it this way,
x.operator=(foo());
The call foo() ends, and then its return value (object) is sent to the
assignment operator. However, the return of foo() is a temporary. The
assignment operator (in Memory header file) takes a reference. Now, the
call to the assignment operator could over-write the return of foo().
That it is not doing so for you is a compiler implementation matter.
Actually, VC++ will not over-write it because it removes temporaries at
end of statement, so the compiler is not complaining. Lint on the other
hand is not aware of that.
The return of foo() is not an lvalue in that it is a compiler
temporary. It is not an object in your source.
Regards,
Dr. Z.
Chief Scientist
zorabi@ZHMicro.com
http://www.zhmicro.com
http://distributed-software.blogspot.com
.

User: "vindhya"

Title: Re: Initializing a non-const reference with non-lvalue 19 Jul 2005 01:49:40 AM
Try this out:
X *y = new X;
return auto_ptr<X>(y);
.


  Page 1 of 1

1

 


Related Articles
 

NEWER

pg.1232     pg.940     pg.716     pg.544     pg.412     pg.311     pg.234     pg.175     pg.130     pg.96     pg.70     pg.50     pg.35     pg.24     pg.16     pg.10     pg.6     pg.3     pg.1

OLDER