I’m pretty new to C++ so this may be a trivial question:
My class has a private member variable that is an array. I need to return that array, but I’m not sure how to do that properly.
class X {
// ...
private: double m_Array[9];
public: double* GetArray() const { return m_Array; }
};
Is there any problem with this code? This returns a pointer to the class member, right? – so if I fetch that array from an instance of this class and modify it (from outside the class), the original class member array will get changed as well? If that is the case, how do I return a copy of the array instead?
Almost – it returns a pointer to the first element of the array.
That’s correct.
The easiest way to achieve that is to use
std::arrayorstd::vectorinstead. You should return aconstreference to it – then the caller avoid the cost of copying when it’s not needed. Example:Alternatively, if the array has a fixed size (as it does in your example), you could return an array contained in a structure – which is what
std::arrayis. Otherwise you could return a pointer (preferably a smart pointer, to avoid memory leaks) to a newly allocated array – which is more or less whatstd::vectoris.