以下代码摘自 Bruce Eckel 的 Thinking in C++ Volume 2 Chapter 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
如果其参数超出范围,则创建名为 RangeError
的嵌套类以在 operator[ ]
中使用。
因为 operator[ ]
返回一个引用,所以它不能返回零。 (没有空引用。)
这是一个真正的异常(exception)情况——您不知道在当前情况下该做什么,并且
你不能返回不可能的值。”
最佳答案
如果函数要返回一个指针而不是一个引用,那么它可以通过返回一个 NULL
指针来表示失败(即越界索引)。但是你不能有 NULL
引用,所以唯一可用的选择是抛出异常。*
正如@Steve 在下面的评论中指出的那样,您不希望 operator[]
返回一个指针,因为这意味着您需要编写如下内容:
T x = *wrapper[5];
* 另一种方法是
断言
。
关于c++ - 为什么作者要强调operator[]不能返回0呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8309668/