Velocity Reviews - Computer Hardware Reviews

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

Thread Tools

Re: Returning valarrays

E. Robert Tisdale
Posts: n/a
Harald Grossauer wrote:

> If I return a valarray as a result of a function
> is then the whole valarray copied onto the stack?

No. Not if you have a good optimizing C++ compiler.

> I.E. if I do a lot of operations on classes containing valarrays,
> say like:
> v1 = v2*(v3+v4/2.0);
> return v1;
> 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)?
> What about the explicit return statement?
> Is the implementation of valarray "clever" enough
> to prevent unnecessary copying by itself?


Suppose that you have a function

myclass f(void) {
myclass t;
// modify t
return t;

A good optimizing C++ compiler should recognize t as an alias
for the return value, call the default constructor
to initialize the return value instead of creating
a local copy of t, copying it to the return value
then call the destructor for t.
This is called the Named Return Value Optimization (NRVO).

When you write

myclass x = f();

s good optimizing C++ compiler will allocate storage for x
and pass a reference (or a pointer) to x as a hidden argument to f --
the compiler will write the same code that it would write for

myclass& f(myclass& t) {
// initialize t with the default constructor
// modify t
return t;

The copy constructor is *never* called!

Using expression classes, you can get the C++ compiler
to *fuse* two or more operations for you
according to Bjarne Stroustrup, "The C++ Programming Language",
Chapter 22 Numerics, Section 4 Vector Arithmetic,
Subsection 7 Temporaries, Copying, and Loops, pages 675-7.

Using expression class templates, you can get the C++ compiler
to generate your expression classes automatically
according to Todd Veldhuizen, "The Blitz++ Library"

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 tom_usenet C++ 0 07-01-2003 01:32 PM