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:
- without the creation of temporaries?
- 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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…