C++ static const access through a NULL pointer(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.
这篇关于C++ 静态常量访问通过空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 静态常量访问通过空指针


- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- C++ 协变模板 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01