通过一个NULL指针的静态const访问

通过一个NULL指针的静态const访问

本文介绍了C ++通过一个NULL指针的静态const访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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":

根据以下示例:

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 ++通过一个NULL指针的静态const访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 18:35