c++ - 使用引用比使用指针的优势是否证明偶尔出现 "null-references"是合理的?

标签 c++ pointers reference null-pointer

我目前正在设计一个大致如下所示的类层次结构:

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/

相关文章:

c++ - 从 Pulse Audio 运行简单的 C 程序时出错

c++ - 为什么基类函数没有被同名的派生类函数隐藏

c - 示例中的指针

c++ - std::reference_wrapper 和简单指针有什么区别?

python - NumPy 中的引用行为明显不一致

c++ - 比较未知数量变量的宏 C++

c++ - CreateFile,ReadDirectoryChanges 问题

c++ - 等于运算符 : pointer to a member function

c# - 从 c# 代码传递结构引用以调用在其原型(prototype)中接受结构引用的 c++ DLL 函数

c++ - 使用 *this 初始化引用