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

前端 未结 4 1392
忘掉有多难
忘掉有多难 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:27

    First, it depends on what you mean by array. With the usual C++ meaning (std::vector), there will never be any problem with memory leaks; with the usual C meaning (T[]), B = f( A ) is an illegal. If you define your own array type, then it should behave more or less like std::vector in this respect.

    With regards to extra temporaries: f should take its argument as a const reference, so that there will be no copying to pass the argument. As for the return value, there is formally a copy, but the compiler is allowed to alide it, and most do, at least some of the time. In an assignment statement, the actual data of the array will probably be copied in the assignment itself.

    In C++11, you can provide a move constructor and a move assignment operator, and (probably) reduce the chances of a copy even more.

提交回复
热议问题