Lets say I have the following:
struct point
{
double x;
double y;
double z;
};
I can write the following:
void point_mult(point& p, double c) { p.x *= c; p.y *= c; p.z *= c; }
void point_add(point& p, const point& p2) { p.x += p2.x; p.y += p2.y; p.z += p2.z; }
So I can then do the following:
point p{1,2,3};
point_mult(p, 2);
point_add(p, point{4,5,6});
This requires no copies of point
, and only two constructions, namely the construction of point{1,2,3}
and the construction of point{4,5,6}
. I believe this applies even if point_add
, point_mult
and point{...}
are in separate compilation units (i.e. can't be inlined).
However, I'd like to write code in a more functional style like this:
point p = point_add(point_mult(point{1,2,3}, 2), point{4,5,6});
How can I write point_mult
and point_add
such that no copies are required (even if point_mult
and point_add
are in separate compilation units), or is functional style forced to be not as efficient in C++?