| 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);
.
|
|
|
|

|
Related Articles |
|
|