On Tue, 01 Jul 2003 11:23:49 +0200, Harald Grossauer
<> wrote:
>If I return a valarray as a result of a function, is then the whole valarray
>copied onto the stack? I.E. if I do a lot of operations on classes
>containing valarrays, say like:
>
>v1 = v2*(v3+v4/2.0);
>return v1;
How was v1 declared? Is it the only return statement in the function?
What is the exact return type of the function?
>
>where v* are instances of
>
>class myclass {
> ....// some other variables
> valarray<float> ...;
>}
>
>
>is then a complete valarray copied for every intermediate result of the
>right hand side (i.e. for each call of the copy constructor)?
Yes, you will get intermediate results that the compiler will not be
able to optimize out. The solution to this is complex, but others have
done the work for you using expression templates. The best known
library is Blitz++. See
www.oonumerics.org
>What about the explicit return statement?
If your compiler implements the Named Return Value Optimization (at
least G++ 3.3+ does, probably many others too), then it should
optimize out the copy in the following circumstances:
a) The type of the returned element matches the return type of the
function.
b) The type that the returned element is copied into matches the
return type of the function
c) All return statements in the function return the same named object.
>Is the implementation of valarray "clever" enough to prevent unecessary
>copying by itself?
No, not really. It is up to the compiler, and the compiler probably
won't do a very good job.
Tom