You are not logged in.
The expression
AA = BB * CC;
is evaluated making calling the operator* on B and C, possible code:
T operator*(const T& A, const T& B) {
T rv(A);
rv *= B;
return rv;
}
where *= does the 'right thing' for the type T.
Just after there is the assignment, possible code:
T& operator=(T rhs) {
rhs.swap(*this);
return *this;
}
Where swap() swaps (doh) without throwing exceptions.
At the moment it should goes that way:
rv is made and returned,
rv is copied in rhs,
rv is destroyed,
rhs swapped with AA,
a reference to AA is returned, but now AA contains the intended value,
rhs is destroyed, now it contains the old AA value.
Is it possible to avoid the double copy? i.e., using rv directly in the assignment?
I recall something about overloading the ternary operator, but seeking on google I find only stuff about :?, so I guess I recall wrongly.
Last edited by ezzetabi (2008-03-21 09:55:13)
Offline
Can you clarify for me please... for you class T, the * operator needs to be defined but the *= operator works? That just seems really, really strange.
Evaluation and assignment without temporaries is possible in C++ but it uses very advanced template overloading. Look up "expression templates" if you are interested.
Also, ?: is the only ternary operator in C++.
Offline
no, no... of course not. I just wanted avoid writing:
possible code:
T& operator*=(const &T rhs) {
//does *this * rhs placing the result in *this
return *this;
}
expression templates you said? I'll look into it.
And... Yes, I never said it is was a noob question.
Thanks.
Offline
Hi there, I'm not sure if I understand your question right, but what about trying this:
T& operator=(T &rhs) {
rhs.swap(*this);
return *this;
}
rhs is now just a reference and no call by value will happen and no copying is involved. Dunno if this helps..
Cheers,
mfa
Offline
mfa, maybe in the expression a=b*c; it works.
But I am worried about the more usual a=b;
A=B;
means A.operator=(B), after the assignment B will be equal to the old A since you swapped into real B not in a copy...
Offline