Here is my example classes :
template<typename T> class MyClassVector
{
public:
inline const std::vector<T>& data() const
{
return _data;
}
protected:
std::vector<T> _data;
};
template<typename T, unsigned int SIZE> class MyClassArray
{
public:
inline const /* SOMETHING */ data() const
{
return _data; // OR SOMETHING ELSE
}
protected:
T _data[SIZE];
};
My question is : what is the equivalent of the MyClassVector data() function for the MyClassArray class to return a constant reference to the underlying _data container ?
Thank you very much !
You want to return a const reference when you return a property of an object, that you want not to be modified out-side of it. For example: when your object has a name, you can make following method const std::string& get_name(){ return name; }; . Which is most optimal way.
Then, no, you can't do that; in a const method you have a const this pointer (in your case it would be a const Foo * ), which means that any reference you can get to its fields1 will be a const reference, since you're accessing them through a " const path".
Not just a copy; it is also a const copy. So you cannot modify it, invoke any non-const members from it, or pass it as a non-const parameter to any function. If you want a modifiable copy, lose the const decl on protos .
There are two ways to do this: The direct and the readable:
Direct:
inline T const (& data() const)[SIZE] {
return _data;
}
Readable:
typedef T Data[Size];
inline Data const& data() const {
return _data;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With