Andrey Tarasevich
11/23/2008 1:00:00 AM
Singulus wrote:
>
> 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:
Huh? The return value of both of the above functions is a temporary. One
is qualified with 'const' the other is not, but both are temporaries. So
what does "prevents [...] to be used as a temporary" supposed to mean?
> GetSomeType().DoStuff();
Firstly, this will work for const-methods regardless of whether you add
'const' to the return type or not. What you were trying to do,
apparently, is prohibit modifying operations on the temporary. This
might be a good idea in many cases. But, secondly, there are q few
pretty useful programming techniques out there which rely on this
temporary being modifiable.
> 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
So far you failed to explain why one is "GOOD' and other is "BAD".
> 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();
Firstly, you started from an attack on "temporaries", and then suddenly
switched to this code, where there are no temporaries. Where's the
connection? Secondly, there's absolutely no "nonsense" in this code.
Some people (me included) might consider it a bad style, by in any case
it is a matter of personal style.
> 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 still won't prevent us from invoking a const-method on the result of
the assignment
class SomeType
{
const SomeType & operator=( const SomeType & lhs );
void DoStuff() const;
};
SomeType t, u;
...
(t = u).DoStuff();
You need to decide what is it you are trying to prevent from happening
and work from there. At this time you don't seem to have a clear idea.
--
Best regards,
Andrey Tarasevich