Initializing a non-const reference with non-lvalue

A

Andrew Ward

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.
 
Z

Zorro

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
(e-mail address removed)
http://www.zhmicro.com
http://distributed-software.blogspot.com
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top