eliminating temporaries

Aug 30, 2010 at 9:57am
I have two objects, basically multidimensional arrays
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class obj1
{
public:
  double& operator ()(unsigned, unsigned);
 // ...
private:
  double *data; 
 // ....
};

class obj2
{
public:
  double& operator ()(unsigned, unsigned, unsigned, unsigned);
  // ...
private:
  double *data; 
  // ....
}

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?
Last edited on Aug 30, 2010 at 10:00am
Aug 30, 2010 at 10:34am
Have you confirmed that any extra temporaries are created? Usually there are none (when the compiler can apply RVO).
Aug 30, 2010 at 10:40am
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.
Aug 30, 2010 at 10:54am
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()
Aug 30, 2010 at 10:58am
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.
Aug 30, 2010 at 11:10am
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).
Topic archived. No new replies allowed.