First, I want to make it clear that I'm not optimizing performance. I'm just seeking knowledge.
Here's a structure:
struct Thing
{
int a,b,c,d,e,f,g,h;
Thing(int fa,int fb,int fc,int fd,int fe,int ff,int fg,int fh)
: a(fa),b(fb),c(fc),d(fd),e(fe),g(fg),h(fh) {}
Thing& operator += (const Thing &t)
{
a+=t.a;
b+=t.b;
c+=t.c;
d+=t.d;
e+=t.e;
f+=t.f;
g+=t.g;
h+=t.h;
return *this;
}
Thing operator + (const Thing &t) const
{
return Thing(a+t.a,b+t.b,c+t.c,d+t.d,e+t.e,f+t.f,g+t.g,h+t.h);
}
void AsSum(const Thing &ta,const Thing &tb)
{
a=ta.a+tb.a;
b=ta.b+tb.b;
c=ta.c+tb.c;
d=ta.d+tb.d;
e=ta.e+tb.e;
f=ta.f+tb.f;
g=ta.g+tb.g;
h=ta.h+tb.h;
}
}
With the above structure, which of these would be more efficient?
Thing first, second; //(assume these already contain interesting data)
1: // This would create a temporary storage structure, but is the nicest to use
Thing third = first + second;
2: // This doesn't create a temporary storage structure
Thing third = first;
third += second;
3: // The only drawback here is that it doesn't assign on construction
Thing third;
third.AsSum( first, second );
Would a compiler normally optimize code like that in 1 to not create temporary storage, even if the operator code is not inlined? A class/struct could define specific behavior for + and +=, so it's hard to imagine how it would manage that.
Do any of you find yourself using code like 2 or 3 in any situations at all? For example, if the struct is huge, or needs to run complex constructor routines?
Thanks for any information.