gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:17:13 26 4
gpt4 key购买 nike

class Foo {
public:
static const int kType = 42;
};

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

这是定义的行为吗?我通读了 C++ 标准,但找不到任何有关访问这样的静态 const 值的信息……我检查了 GCC 4.2、Clang++ 和 Visual Studio 2010 生成的程序集,但它们都没有执行 NULL 的取消引用指针,但我想确定一下。

最佳答案

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

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
}

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

关于通过 NULL 指针访问 C++ 静态常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3498444/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com