Foo(300) = Foo(500); Why does a compiler compile that?

A

Alex Vinokur

Compiler GNU gpp.exe (GCC) 3.4.1

Foo(300) = Foo(500); // Foo(300) is const. Why does a compiler compile that?


------ foo.cpp ------
struct Foo
{
explicit Foo(int) {}

Foo& operator= (const Foo&)
{
return *this;
}
};

int main()
{
Foo var1(100);
const Foo var2(200);

var1 = Foo(500);
Foo(300) = Foo(500); // Foo(300) is const. Why does a compiler compile that?
// var2 = Foo(500); // A compiler doesn't compile that

return 0;
}
 
I

Ivan Vecerina

Alex Vinokur said:
Compiler GNU gpp.exe (GCC) 3.4.1

Foo(300) = Foo(500); // Foo(300) is const. Why does a compiler compile
that?

Foo(300) is not const - it is a temporary.
It is true that temporaries can be bound to a const reference only
(not to a non-const ref).
However, it is legal to call any member function on a temporary.
And the line above is equivalent to:
Foo(300).operator=( Foo(500) );

This is indeed a case where user-defined classes do not behave
like built-in types...


Cheers,
Ivan
 
A

Alex Vinokur

Ivan Vecerina said:
Foo(300) is not const - it is a temporary.
If 'Foo(300) = Foo(500);' is legal, why can temporaries be bound to a const reference only (not to a non-const ref)?
---------------------------------------
However, it is legal to call any member function on a temporary.
And the line above is equivalent to:
Foo(300).operator=( Foo(500) );

This is indeed a case where user-defined classes do not behave
like built-in types...
[snip]
 
I

Ivan Vecerina

Alex Vinokur said:
If 'Foo(300) = Foo(500);' is legal, why can temporaries be bound
to a const reference only (not to a non-const ref)?

Probably to avoid programming errors such as:
copySomeMembers( myTargetVariable, getSomeTemporary() );
//woops: actually, the functions takes 1st source, 2nd destination:
// copySomeMembers( Foo const& src, Foo& dst );
Because temps can only be bound to a const reference, you cannot
accidentally pass a temporary for the output of a function.
I find this is a good thing, but some disagree.
On the other hand, it is sometimes convenient (and somewhat less
error prone) to write something like:
getSomeTermporaryHandle().doSomething();
And there is no special treatment for assignment operators,
which is just another member function.

I think a balance had to be chosen between convenence
and safety.



Ivan
 
M

Matthew Schaefer

I think the problem is the following:
1) Foo(300) is non-const.
2) your operator= function does nothing. It simply assigns the lhs back
to itself. It does not check that the members of lhs and rhs are equal.
 

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,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top