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++ 静态常量访问通过空指针


基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01