By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,110 Members | 1,406 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,110 IT Pros & Developers. It's quick & easy.

Initializing a non-const reference with non-lvalue

P: n/a
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
&' 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?

Jul 23 '05 #1
Share this Question
Share on Google+
2 Replies

P: n/a
Try this out:

X *y = new X;
return auto_ptr<X>(y);

Jul 23 '05 #2

P: n/a
Lint is correct. Look at it this way,


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.

Dr. Z.
Chief Scientist

Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.