为什么作者强调运算符[]不能返回0 ?

Why does the author emphasizes the fact that operator[] cannot return 0?

本文关键字:不能 返回 运算符 为什么      更新时间:2023-10-16

下面的代码摘自Bruce Eckel的《Thinking in c++ Volume 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;
    }
}

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

" PWrap模板显示了比您目前看到的更典型的异常用法:a如果operator[ ]的参数超出范围,则创建名为RangeError的嵌套类在CC_4中使用。因为operator[ ]返回一个引用,所以它不能返回0。(没有空引用。)这是一个真正的异常情况—您不知道在当前上下文中该做什么,并且你不能返回一个不可能的值。"

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

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

T x = *wrapper[5];


他强调了这一点,以解释为什么在这种情况下抛出异常是唯一的选择。

如果操作符返回一个指针,它可以返回一个空指针,而不是在发生错误时抛出异常。但是,由于它返回一个引用,并且没有空引用这样的东西,因此处理错误的唯一方法是抛出异常。

作者解释得很好,也许零部分是消耗的,他的意思是他不能返回任何表示缺乏值的值(例如空指针),因此抛出合适

作者已经说过"因为operator[]返回一个引用,所以它不能返回零"。因为NULL引用是一个非常糟糕的东西