"Shachar Shemesh" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> Hi all,
>
> Here is a small program for your viewing pleasure:
>
> > class a {
> > public:
> > explicit a(int param);
> >
> > a &operator= ( a &that );
> > };
> >
> > int main()
> > {
> > a var1(3);
> >
> > var1=a(5);
> >
> > return 0;
> > }
>
> Somewhat surprisingly, this does not compile:
> g++ -Wall -g testcompile.cc -o testcompile
> testcompile.cc: In function `int main()':
> testcompile.cc:12: error: no match for 'operator=' in 'var1 = a(5)'
> testcompile.cc:5: error: candidates are: a& a::operator=(a&)
> make: *** [testcompile] Error 1
>
> There are two things that can make it compile. One is to add a "const"
> at the "operator=" definition, and the other is to use an explicit
> variable (i.e. - not a temporary one).
>
> The reason for this failure seems to be that g++ treats temporary
> variables as consts. I see neither reason nor logic for this decision,
> however. Why can't I modify temporary variables if I so wish? Don't they
> have a well defined life span (until the end of the statement) for a reason?
>
[snip]
Foo(5) is constant, so 'Foo& operator= (const Foo&)' is applied.
------ foo.cpp : BEGIN ------
#include <iostream>
#include <cassert>
using namespace std;
struct Foo
{
explicit Foo(int) {}
Foo (const Foo&) {assert (0);} // Copy constructor is not invoked
Foo& operator= (Foo &that)
{
cout << __PRETTY_FUNCTION__ << endl;
if (!(&that == this)) /* Do something */ ;
return *this;
}
Foo& operator= (const Foo &that) // 'const' has been added
{
cout << __PRETTY_FUNCTION__ << endl;
if (!(&that == this)) /* Do something */ ;
return *this;
}
};
int main()
{
Foo var1(3);
Foo var2(4);
var1 = Foo(5); // Foo& operator= (const Foo &that) is applied, because
Foo(5) is constant
var1 = var2; // Foo& operator= (Foo &that) is applied
return 0;
}
------ foo.cpp : END --------
------ Compilation & Run : BEGIN ------
$ gpp --version
gpp.exe (GCC) 3.4.1
[---omitted---]
$ gpp -W -Wall foo.cpp
// No errors/warnings
$ ./a.exe
Foo& Foo::operator=(const Foo&)
Foo& Foo::operator=(Foo&)
------ Compilation & Run : RUN --------
--
Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn
=================================================================
To unsubscribe, send mail to [EMAIL PROTECTED] with
the word "unsubscribe" in the message body, e.g., run the command
echo unsubscribe | mail [EMAIL PROTECTED]