I am new to c++ and got really confused about this class of numerical array I am trying to implement. I hope somebody can give me some advice:
class ndarray {
public:
double *data;
...
ndarray(...) { \* code to dynamically allocate data *\}
ndarray(const ndarray& A) { \* code to copy construct *\}
~ndarray() { \* code to delete data *\};
ndarray& operator=(const ndarray& A) {\* code to deep copy *\}
friend ndarray& log(const ndarray& A) {
ndarray B(...);
\* code to popularize B[i] with log(A[i]) *\
return B; }
};
int main() {
ndarray A(...), B(...);
B=log(A);
}
Here I overloaded the =
operator to deep copy the data elements. After inserting some outputs to the code I found that the B=log(A)
code has called the =
operator explicitly by creating and popularizing a new data array elementwise, even though the overloaded log
function returns by reference. My question is, how can I avoid this extra copying of data elementwise and use the ndarray
object created by log
function directly. Obviously the compiler is not helping me in this case.