问题描述
我可以从一个空指针调用一个类的非静态,非虚方法吗?然后成员函数会测试这个== nullptr,如果它是真的,立即返回。
Can I call a non-static, non-virtual method of a class from a null pointer? The member function would then test if this==nullptr, and return immediately if it's true.
我知道它将在大多数情况下工作,但这是一个保证结果?这样,我可以确保空指针异常永远不会发生,并避免在调用者代码的许多地方测试空指针。这是为了紧凑,我现在不会这样做,但我很想知道,如果任何标准将保证这个工作...
I know it will work in most cases, but is this a guaranteed result? That way, I can ensure null pointer exceptions never happen, and avoid testing for null pointers in many places of the caller code. That's for compactness, I'm not going to do that right now, but I'm curious to know if any standard will guarantee this to work...
谢谢!
推荐答案
取消引用 nullptr
是未定义的行为。期间!
在某个特定实现上是否有效是无关紧要的,不能保证其行为。
Dereferencing a nullptr
is Undefined behavior. Period!
Whether it works or not on one particular implementation is irrelevant, the behavior is not guaranteed.
这篇关于C ++从空指针调用非虚拟非静态方法,无需访问成员:这是否保证工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!