Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Re: Returning valarrays

Thread Tools

Re: Returning valarrays

Posts: n/a
On Tue, 01 Jul 2003 11:23:49 +0200, Harald Grossauer
<(E-Mail Removed)> 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

>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
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.

Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Presentation and help with class containing two valarrays C++ 5 02-23-2007 07:04 PM
how to best use valarrays as constructor arguments Gerard Kramer C++ 9 07-10-2006 06:27 PM
valarrays and regular arrays Sebastian Thiebes C++ 3 06-10-2004 08:43 AM
C++ STL valarrays vs. vectors Michael Aramini C++ 10 11-03-2003 11:15 AM
Re: Returning valarrays E. Robert Tisdale C++ 0 07-01-2003 04:19 PM