C++ 静态常量访问通过空指针

2021-12-13 00:00:00 pointers static c++
class Foo {
public:
 static const int kType = 42;
};

void Func() {
 Foo *bar = NULL;
 int x = bar->kType;
 putc(x, stderr);
}

这是定义的行为吗?我通读了 C++ 标准,但找不到任何关于访问静态常量值的信息......指针,但我想确定一下.

Is this defined behavior? I read through the C++ standard but couldn't find anything about accessing a static const value like this... I've examined the assembly produced by GCC 4.2, Clang++, and Visual Studio 2010 and none of them perform a dereference of the NULL pointer, but I'd like to be sure.

推荐答案

您可以使用指针(或其他表达式)来访问静态成员;然而,不幸的是,通过 NULL 指针这样做是官方??未定义的行为.来自 9.4/2 静态成员":

You can use a pointer (or other expression) to access a static member; however, doing so through a NULL pointer unfortunately is officially undefined behavior. From 9.4/2 "Static members":

类 X 的静态成员 s 可能是使用限定 ID 引用表达式 X::s;这不是必要的使用类成员访问语法(5.2.5) 引用静态成员.一个静态成员可以使用类成员访问语法,in在这种情况下,对象表达式是评估.

A static member s of class X may be referred to using the qualified-id expression X::s; it is not necessary to use the class member access syntax (5.2.5) to refer to a static member. A static member may be referred to using the class member access syntax, in which case the object-expression is evaluated.

基于以下示例:

class process {
public:
    static void reschedule();
};

process& g();

void f()
{
    process::reschedule();   // OK: no object necessary
    g().reschedule();        // g() is called
}

目的是让您确保在这种情况下会调用函数.

The intent is to allow you to ensure that functions will be called in this scenario.

相关文章