and some function obj2 func1(const obj1&);.
Now I want to use it like
1 2 3 4 5 6
obj1 *objects;
obj2 avg2 = 0;
for(int i = 0; i < i_max; i++)
{
avg2 += func1(objects[i]);
}
The question is how can I write my function(and/or obj2) to eliminate temporaries creation, which can be quite expensive here.
PS: fortran-like syntaxis func1_acc(const obj1&, obj2&);is ugly, I am looking for a real C++ solution. Is there any?
It may not be as expensive as you think. Temporaries are not going to duplicate your arrays. They will only duplicate the pointers to the arrays. I would think that optimisation and inlining will minimise the temporaries.
Maybe you can return a reference to a obj2 from func1, from a static obj2 in func1 for example? (and overload operator += if needed by your type). That won't be threadsafe of course
Also, but i'm not sure if it's a lot different once compiled, if you defined func1 as a method of obj1, you could do objects[i]->func1() instead of func1(objects[i]), removing an argument from func1()
Have you confirmed that any extra temporaries are created? Usually there are none (when the compiler can apply RVO).
How do I do that? If I add some output to the constructor, that would probably break RVO, and my assembly knowledge is too limited for that kind of analysis.
It may not be as expensive as you think. Temporaries are not going to duplicate your arrays. They will only duplicate the pointers to the arrays. I would think that optimisation and inlining will minimise the temporaries.
inlining is not really an option for that function and for temporaries memory (huge) will be allocated, not just a pointer.
How do I do that? If I add some output to the constructor, that would probably break RVO, and my assembly knowledge is too limited for that kind of analysis.
Adding an output statement to the copy constructor should not break RVO, but it'll show you how many copies are created (if any).