Re: Using assignment operator when rhs is temporary object.
Vladimir Grigoriev wrote:
I have found a difference in behavior of a Borland C++ compiler and Visual
C++ 2005 EE compiler.
class A
{
public:
A( int i = 0 ): a( i ) {}
A( A &rhs ): a( rhs.a ) {}
virtual ~A(){}
A & operator=( A &rhs ) // without const!
{
if ( this != &rhs )
{
a = rhs.a;
}
return ( *this );
}
virtual std::ostream & out( std::ostream &os ) const
{
os << a;
return ( os );
}
private:
int a;
};
inline std::ostream & operator<<( std::ostream &os, const A &rhs )
{
return ( rhs.out( os ) );
}
A f()
{
return ( A( 5 ) );
}
int _tmain(int argc, _TCHAR* argv[])
{
A a1( 10 );
A a2;
a2 = f();
return 0;
}
For the Borland C++ compliker the compilation is failed as the compiler does
not find a required function for the assignment statement a2 = f();
because the assignment operator has no attribute const for rhs parameter
while Visual C++ compiles the code without any error.
Which compiler is wrong according to the C++ standard?
Visual C++ is not wrong because you're most likely have C++ extensions
enabled. See in the settings: C/C++ | Language | Disable Language
Extensions. If extensions are not disabled, VC++ allows you to bind a
reference to non-const to a temporary. The Standard does not allow
that. As soon as you disable the extensions, you will get an error from
VC++ as well, IIRC. The problem, of course, is that with extensions
disabled, no Windows header will compile. :-)
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask