S
Singulus
Introduction:
It is good advice to write the return type of a function that returns
by value as a const:
SomeType GetSomeType(...); // BAD
const SomeType GetSomeType(...); // GOOD
The above is good because it prevents the function return value to be
used as a temporary:
GetSomeType().DoStuff();
This is especially useful in the case of operator functions that
creates objects, for example:
Vector3 operator+( const Vector & lhs, const Vector & rhs ); // BAD
const Vector3 operator+( const Vector & lhs, const Vector & rhs ); //
GOOD
(vec1 + vec2).Normalize(); // BAD variant pass this non-nonse, GOOD
stops it at compile time
The Question:
Why the same principle is not used for the copy assignment of classes?
Currently, the canonical copy assignment operator function prototype
is written like this:
class SomeType
{
SomeType & operator=( const SomeType & lhs );
};
This will pass a non-sense code like the following. The non-sense is
not the same as with the temporary objects but still is not the best
that can be done to restrict the writing of non-sense which is quite
easily and often unforgiving with C++:
SomeType t, u;
....
(t = u).DoStuff();
If we write simply append a const, this will still preserve the
behaviour when we have a chain of assignments because the function
itself takes a const reference to an object of the same class, so it
matches with the return value:
class SomeType
{
const SomeType & operator=( const SomeType & lhs );
};
SomeType t, u, v;
....
t = u = v;
It is good advice to write the return type of a function that returns
by value as a const:
SomeType GetSomeType(...); // BAD
const SomeType GetSomeType(...); // GOOD
The above is good because it prevents the function return value to be
used as a temporary:
GetSomeType().DoStuff();
This is especially useful in the case of operator functions that
creates objects, for example:
Vector3 operator+( const Vector & lhs, const Vector & rhs ); // BAD
const Vector3 operator+( const Vector & lhs, const Vector & rhs ); //
GOOD
(vec1 + vec2).Normalize(); // BAD variant pass this non-nonse, GOOD
stops it at compile time
The Question:
Why the same principle is not used for the copy assignment of classes?
Currently, the canonical copy assignment operator function prototype
is written like this:
class SomeType
{
SomeType & operator=( const SomeType & lhs );
};
This will pass a non-sense code like the following. The non-sense is
not the same as with the temporary objects but still is not the best
that can be done to restrict the writing of non-sense which is quite
easily and often unforgiving with C++:
SomeType t, u;
....
(t = u).DoStuff();
If we write simply append a const, this will still preserve the
behaviour when we have a chain of assignments because the function
itself takes a const reference to an object of the same class, so it
matches with the return value:
class SomeType
{
const SomeType & operator=( const SomeType & lhs );
};
SomeType t, u, v;
....
t = u = v;