在C++中为向量容器重载[]运算符时,我为未定义的索引返回什么?

Sas*_*yal 3 c++ c++11

我刚开始用C++实现一个基本的向量容器.它还远未完成,但它看起来像这样:

using namespace std;

typedef unsigned  long long int bigInt;

namespace stl2{
    template<class T>
    class vector{
    private:
        bigInt l;
        bigInt cap;
        T* arr;
    public:
        vector(){
            cap = 0;
            l = 0;
        }

        ~vector(){
            if (cap > 0) delete[] arr;
        }

        vector(bigInt size){
            cap = size;
            l = size;
            arr = new T[size];
        }

        vector(bigInt size, const T& def) : vector(size){
            for (bigInt i = 0; i < size; i++){
                arr[i] = def;
            }
        }

        bigInt size(){
            return l;
        }

        bigInt length(){
            return l;
        }

        bigInt capacity(){
            return cap;
        }

        void resize(bigInt size){
            if (size < cap) return;
            l = size;
            cap = size;
        }

        void push_back(const T& data){
            // Check if vector is full
            if (l == cap) {
                //Copy all elements of this vector to another
                if (cap == 0)
                    cap = 1;
                else
                    cap *= 2;
                T* temp = new T[cap];
                for (int i = 0; i < l; i++){
                    temp[i] = arr[i];
                }
                delete[] arr;
                arr = temp;
            }
            arr[l] = data;
            l++;
        }

        //Operators
        T& operator[](bigInt index){
            if (index < cap)
                return arr[index];
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

所以我的[]运算符有问题.我知道如果索引<capacity,我可以返回arr [index].但是如果索引大于或等于容量,我该返回什么?由于我返回对元素的引用,因此无法返回值.

ala*_*ain 9

std::vector使用时,抛出异常at()与无效的指数,你可以做同样的.

operator[]std::vector但是不执行边界检查,使用无效指数是不确定的行为.