Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 views
in Technique[技术] by (71.8m points)

c++ - Implementing B=f(A), with B and A arrays and B already defined

Suppose I have an array B that has been already defined and used somewhere in a C++ code. Now, suppose that I have another array A that has been defined and initialized. I want to create a function f that transforms A (for example, an FFT) and I want that the result of the transformation is assigned to B (of course, following the transformation of A, B will change its values). I want to do all that by keeping the syntax

B=f(A);

namely, without passing the address of B as an argument to f. Is it possible:

  1. without the creation of temporaries?
  2. with the creation of temporaries, but without memory leaks?

Thank you.

EDIT: SUMMARY OF THE SOLUTIONS PROVIDED IN THE ANSWERS BELOW

Thanks to RiaD, James Kanze, Shahbaz and Razispio for their answers.

What I'm asking requires A and B to be objects of an array class in order to gain efficiency and effectiveness. Also, in a "standard" implementation, e.g., with an array class equipped with a copy constructor, a syntax like B=f(A); would require the creation of temporaries. It should be however mentioned that temporaries are not necessarily a limitation, since many compilers would be able to elide the extra temporaries. Opposite to this, a syntax like f(A,B); would avoid temporaries. The solution using expression templates enables the syntax B=f(A); while internally using f(A,B);, making the use of temporaries negligible. An efficient alternative solution would be using move assignment operators, see for example

Move semantics and rvalue references in C++11

For details, see the answers kindly provided below.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The easiest way it to use std::vector or std::array

example:

vector<int> f(const vector<int>& a) {
   return a;
}

b = f(a);

Actually, you don't have to use one of this classes to store, you may use your own class, that have operator =

YourClass& operator = (const vector<int>&/* there will be returned value of f, it may be std::array, std::vector or your own class.*/ v) {
    //fill it here.
    return *this;
}

You may also provide move constructor for it to avoid unnecessary copying.

for example

class Array {
    int* data;   
    YourClass& operator = (YourClass&& v) {
        swap(v.data, data);
    }
}

YourClass f(const YourClass& a) {
   //
}

Array a,b;
b = f(a);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...