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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)