我目前正在设计一个大致如下所示的类层次结构:
struct Protocol
{
// Pass lower-layer protocol as a reference.
Protocol(Protocol & inLLProtocol) :
mLLProtocol(inLLProtocol)
{
}
// A protocol "always" has a LLProtocol.
Protocol & mLLProtocol;
};
struct Layer1Protocol : Protocol
{
// This is the "bottom" protocol, so I pass a fake reference.
Layer1Protocol() : Protocol(*static_cast<Protocol*>(nullptr)) {}
};
IIRC 绑定(bind)对 *nullptr
的引用是安全的,只要引用永远不会被访问。所以现在我有责任设计我的 Layer1Protocol 类以防止这种情况发生。
我喜欢这种方法,因为我确保所有用户协议(protocol)实例将引用它们各自的下层协议(protocol)(Layer1Protocol 是异常(exception),但它是核心库的一部分)。我认为这比使用指针更好,因为一旦引入指针,就可以传递空指针,然后可能需要在运行时检查,结果是大量指针检查代码和偶尔的错误。
您认为我的基于引用的方法站得住脚吗?还是使用空引用总是不好的做法?
最佳答案
IIRC binding a reference to *nullptr is safe as long as the reference is never accessed.
不,取消引用 nullptr
始终是未定义的行为。在正确的程序中不能有“空引用”。
关于c++ - 使用引用比使用指针的优势是否证明偶尔出现 "null-references"是合理的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10752218/