Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a const reference to a C-array?

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 !

like image 467
Vincent Avatar asked Aug 08 '12 03:08

Vincent


People also ask

How do I return a const reference?

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.

Can a const function return a reference?

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".

Can you copy a const reference?

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 .


1 Answers

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;
}
like image 126
bitmask Avatar answered Oct 09 '22 09:10

bitmask