You are not logged in.

#1 2008-03-21 09:33:35

ezzetabi
Member
Registered: 2006-08-27
Posts: 947

More efficient A=B*C; of class type? C++

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

#2 2008-03-21 09:53:27

Allan
Pacman
From: Brisbane, AU
Registered: 2007-06-09
Posts: 11,385
Website

Re: More efficient A=B*C; of class type? C++

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

#3 2008-03-21 09:57:23

ezzetabi
Member
Registered: 2006-08-27
Posts: 947

Re: More efficient A=B*C; of class type? C++

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

#4 2008-03-21 11:50:02

mfa
Member
Registered: 2007-10-04
Posts: 19

Re: More efficient A=B*C; of class type? C++

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

#5 2008-03-21 12:04:48

ezzetabi
Member
Registered: 2006-08-27
Posts: 947

Re: More efficient A=B*C; of class type? C++

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

Board footer

Powered by FluxBB