为什么作者强调operator []不能返回0的事实?

Bel*_*loc 4 c++

下面的代码是从Bruce Eckel在C++第2卷第16章中的思考中复制而来的

//: C07:Wrapped.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Safe, atomic pointers

#include <fstream>
#include <cstdlib>
using namespace std;
ofstream out("wrapped.out");

// Simplified. Yours may have other arguments.
template<class T, int sz = 1> class PWrap
{
    T* ptr;

    public:
    class RangeError {}; // Exception class
    PWrap() { ptr = new T[sz]; out << "PWrap constructor" << endl; }
    ~PWrap() { delete []ptr; out << "PWrap destructor" << endl; }
    T& operator[](int i) throw(RangeError)
    {
        if(i >= 0 && i < sz) return ptr[i];
        throw RangeError();
    }
};

class Cat
{
    public:
    Cat() { out << "Cat()" << endl; }
    ~Cat() { out << "~Cat()" << endl; }
    void g() {}
};

class Dog
{
    public:
    void* operator new[](size_t sz) { out << "allocating a Dog" << endl; throw int(47); }
    void operator delete[](void* p) { out << "deallocating a Dog" << endl; ::delete p; }
};

class UseResources
{
    PWrap<Cat, 3> Bonk;
    PWrap<Dog> Og;

    public:
    UseResources() : Bonk(), Og() { out << "UseResources()" << endl; }
    ~UseResources() { out << "~UseResources()" << endl; }
    void f() { Bonk[1].g(); }
};

int main()
{
    try
    {
        UseResources ur;
    }
    catch(int)
    {
        out << "inside handler" << endl;
    }
    catch(...)
    {
        out << "inside catch(...)" << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

我对代码本身没有任何问题.但是我在理解关于类异常的以下注释时遇到了一些麻烦RangeError:

" PWrap模板显示了比你到目前为止看到的更典型的异常使用:如果参数超出范围RangeError,operator[ ]则创建一个被调用的嵌套类.因为operator[ ]返回引用它不能返回零.(没有空引用.)这是一个真正的例外情况 - 你不知道在当前的情况下该做什么,你不能返回一个不可能的值."

Oli*_*rth 7

如果函数返回指针而不是引用,则它可以通过返回NULL指针来指示失败(即越界索引).但是你不能有NULL引用,所以唯一可用的选择是抛出异常.*

正如@Steve在下面的评论中指出的那样,你不会想要operator[]返回一个指针,因为这意味着你需要写一些像:

T x = *wrapper[5];
Run Code Online (Sandbox Code Playgroud)


*另一种选择是assert.