C++ -- Why not return Array1D&?
template<class T>
class Array2D {
public:
class Array1D {
public:
T& operator[](int index);
const T& operator[](int 开发者_StackOverflow中文版index) const;
...
};
Array1D operator[](int index); // why not return Array1D&
const Array1D operator[](int index) const; // why not return Array1D&
...
};
The above code is used to simulate a two-dimensional array with a class named as Array2D. Here is the question, why we should return Array1D rather than Array1D&?
Thank you
It really depends on the details of Array1D and Array2D. Here's what could make it important to return a copy (rather than a reference).
Suppose that Array1D (let's call these Rows) is just a pair of a pointer to the data, and the integer representing the size of the data. Copying that pair is not a problem (just as fast as returning a reference). Now, suppose that Array2D (let's call it Table) holds those Rows (light-weight pairs) in a vector. Returning a reference to a Row in effect returns a pointer to an element in the Table vector. If you save that reference, and then add more Rows, the vector may get reallocated and your reference would no longer be valid. But the data inside the Rows didn't move, so if you had a copy of that Row (pointer plus size), you could still safely access it.
On the other hand, if Array1D is a vector, for example, with an expensive copy, then returning it by value seems a distinctly bad idea.
Lastly, whoever wrote that code, assuming that return by value was intentional, should have added a comment to explain it :)
You shouldn't. Returning Array1D
makes a copy of the data in Array1D
, so changing any values in it ( like array2d_instance[1][1] = 1;
will not change the value at array2d_instance[1][1]
)
You need to return a reference ( Array1D&
) from operator[]
If returning Array1D
is working, you need to make sure Array1D's copy constructor is properly implemented.
At a guess, it looks pretty similar to a 3D matrix class I posted in a previous answer. If so, the Array1D is just a proxy object -- just a temporary holder for a position in the array/matrix to be used by the next level's operator[] to get the location of an element. In this case, 1) the proxy object is lightweight and cheap to copy so returning a reference wouldn't game much at best, and 2) the object will normally be created only as a temporary (in fact, there's probably no other way to create one) so attempting to use a reference could/would/will lead to a dangling reference. In other words, returning a reference would only increase problems, not efficiency.
精彩评论