c++ - 如何取消引用 nullptr 返回正确的对象?

标签 c++ undefined-behavior

我一直在尝试用 C++ 实现单例类。

#include<iostream>
using namespace std;

class Singleton {
private:
static Singleton* singleton;
public:
static Singleton& Get() {
    return *singleton;
}
static void display() {
    cout << "Hello world\n";
}
};

Singleton* Singleton::singleton = nullptr;
int main() {
Singleton::Get().display();
return 0 ;
}

程序运行良好。 谁能帮我理解取消引用 nullptr 是如何在类的“Get”函数中返回对象引用的。

最佳答案

core language issue 315: Is call of static member function through null pointer undefined? 涵盖了这一点其中说:

Another instance to consider is that of invoking a member function from a null pointer:

  struct A { void f () { } };
  int main ()
  {
    A* ap = 0;
    ap->f ();
  }

Which is explicitly noted as undefined in 12.2.2 [class.mfct.non-static], even though one could argue that since f() is empty, there is no lvalue->rvalue conversion.

If f is static, however, there seems to be no such rule, and the call is only undefined if the dereference implicit in the -> operator is undefined. IMO it should be.

Incidentally, another thing that ought to be cleaned up is the inconsistent use of "indirection" and "dereference". We should pick one. (This terminology issue has been broken out as issue 342.)

This is related to issue 232.

响应是:

We agreed the example should be allowed. p->f() is rewritten as (*p).f() according to 8.2.5 [expr.ref]. *p is not an error when p is null unless the lvalue is converted to an rvalue (7.1 [conv.lval]), which it isn't here.

关于c++ - 如何取消引用 nullptr 返回正确的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53142822/

相关文章:

c - 在 NULL 值(或未定义)指针上重新分配

c++ - 未解析的外部符号 (LNK2019)

C++:对一个空输入使用react与空输入文件

c++ - 在C++/Eclipse中编译Tensorflow时遇到问题

c++ - 在 bool 中设置额外位使其同时为真和假

c++ - 奇怪的 C++ 行为。值被覆盖

c - if((result=f())==0) 是未定义的行为吗?

c - 比较已释放的指针会调用 UB 吗?

c++ - 在这种情况下我的压缩率可以低于 6.25% 吗?

c++ - 使用 VC++ 编译 SQLite 时如何处理警告?