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

前端 未结 4 1393
忘掉有多难
忘掉有多难 2020-12-21 15:54

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 de

4条回答
  •  粉色の甜心
    2020-12-21 16:15

    Since f doesn't have any references to B, it has no way but work on a local array. You would therefore then have to copy the values to B. So in the current form, no there is no way. However, if you make f inline, the optimizer may just help you with that1, but that wouldn't be a good idea for an FFT for example.

    With temporary values but no memory leak, you can simply wrap the array in a class (or use vector which already does that) and return that. Note that non-dynamic-array copy itself doesn't produce memory leaks, it's just not possible in C++ to write some_array = another_array.

    If you have the option for a redesign, best way would be to call f(A, B) for maximum performance,


    1 If the compiler is smart enough, it would recognize that a local array in f is going to be copied over to B, and in the inline version of f it could use B itself since it has access to it.

提交回复
热议问题