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++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01