下面的代碼是從布魯斯Eckel的思考用C++複製第2卷第16章作者爲什麼強調operator []不能返回0的事實?
//: 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
模板顯示一個比較典型的異常的使用比你迄今所看到:所謂RangeError
一個 嵌套類創建如果參數超出範圍,則在operator[ ]
中使用 因爲operator[ ]
返回一個引用,所以它不能返回零(沒有空引用) 這是一個真正的例外條件 - 你不知道在當前上下文中做什麼,和 你不能返回一個不可能的值。「
假設operator []返回一個指針,你將如何測試它的NULL值? – Belloc
@ user1042389:您通常如何測試函數是否返回特定值?就像'T * ptr = something [i]; if(ptr == 0){/ * it null * /} else {/ *不是* /};'。但是,對於重載的'operator []'來說,返回一個指針並不是很有用,因爲它不會導致基於內置版本的操作符的語法。 –
@SteveJessop謝謝史蒂夫。這回答了我的問題。 – Belloc