为什么作者强调运算符[]不能返回0 ?
Why does the author emphasizes the fact that operator[] cannot return 0?
下面的代码摘自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引用是一个非常糟糕的东西
相关文章:
- 为什么模板类中的对象不能返回值
- 为什么我不能返回带有透明函子的法线映射引用?
- 为什么我不能返回向量<向量<int>>(进程返回 -1073741819 (0xC0000005))
- 为什么代码不能返回正确的值?
- 不能返回派生的类(无法转换)
- 为什么VS2017协程不能返回无效?
- 不能返回 if 语句的右边
- 为什么 c# 可以返回对象,而 c++ 在从 STL 容器弹出时不能返回?
- 为什么我不能返回类型定义的引用
- 为什么我不能返回到列表c++
- 为什么可以将枚举作为函数变量传递,但不能返回枚举?
- 为什么作者强调运算符[]不能返回0 ?
- c++服务器,Java InputStreamReader.read不能返回-1,BufferedReader不返回值
- 为什么这段代码不能返回值为505.5的bpeeffect变量?
- c++ 11基于范围的multimap循环-不能返回非const对
- 使用c++,为什么我不能返回新的字符串作为方法
- 不能返回指向结构体的指针
- 为什么decltype(*this)不能返回正确的类型?
- 为什么方法不能返回多个值
- 为什么我的 constexpr 函数不能返回 lambda?