Re: Returning valarrays

Discussion in 'C++' started by tom_usenet, Jul 1, 2003.

  1. tom_usenet

    tom_usenet Guest

    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
    tom_usenet, Jul 1, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. E. Robert Tisdale

    Re: Returning valarrays

    E. Robert Tisdale, Jul 1, 2003, in forum: C++
    Replies:
    0
    Views:
    404
    E. Robert Tisdale
    Jul 1, 2003
  2. Michael Aramini

    C++ STL valarrays vs. vectors

    Michael Aramini, Sep 2, 2003, in forum: C++
    Replies:
    10
    Views:
    13,086
    vrambati
    Nov 3, 2003
  3. Sebastian Thiebes

    valarrays and regular arrays

    Sebastian Thiebes, Jun 9, 2004, in forum: C++
    Replies:
    3
    Views:
    466
    Marc Schellens
    Jun 10, 2004
  4. Gerard Kramer
    Replies:
    9
    Views:
    372
    Gerard Kramer
    Jul 10, 2006
  5. Replies:
    5
    Views:
    397
    Lionel B
    Feb 23, 2007
Loading...

Share This Page