相关疑难解决方法(0)

C++静态const通过NULL指针访问

class Foo {
public:
 static const int kType = 42;
};

void Func() {
 Foo *bar = NULL;
 int x = bar->kType;
 putc(x, stderr);
}
Run Code Online (Sandbox Code Playgroud)

这是定义的行为吗?我阅读了C++标准但是找不到任何关于访问静态const值的内容......我已经检查了GCC 4.2,Clang ++和Visual Studio 2010生成的程序集,并且它们都没有执行NULL的解引用指针,但我想确定.

c++ static pointers

12
推荐指数
1
解决办法
1919
查看次数

通过空指针获取成员变量的地址是否会产生未定义的行为?

下面的代码(或使用null文字的显式转换来删除临时变量的等效代码)通常用于计算类或结构中特定成员变量的偏移量:

class Class {
public:
    int first;
    int second;
};

Class* ptr = 0;
size_t offset = reinterpret_cast<char*>(&ptr->second) -
                 reinterpret_cast<char*>(ptr);
Run Code Online (Sandbox Code Playgroud)

&ptr->second 看起来它等同于以下内容:

&(ptr->second)
Run Code Online (Sandbox Code Playgroud)

而这相当于

&((*ptr).second)
Run Code Online (Sandbox Code Playgroud)

它取消引用对象实例指针并为空指针产生未定义的行为.

那么原始罚款还是会产生UB?

c++ offset undefined-behavior

12
推荐指数
1
解决办法
555
查看次数

标签 统计

c++ ×2

offset ×1

pointers ×1

static ×1

undefined-behavior ×1