我最近遇到了以下代码:
class Foo
{
public:
void bar();
// .. other stuff
};
void Foo::bar()
{
if(!this) {
// .. do some stuff without accessing any data members
return;
}
// .. do normal actions using data members
}
该代码可以编译,因为在 C++ 中,方法只是隐式传递“this”指针的函数,并且可以像任何其他指针一样检查“this”是否为 NULL。显然,即使这段代码没有崩溃,它也是令人困惑和不好的做法;在调试器中单步执行代码会非常令人困惑,看到 NULL 指针即将调用它的方法,然后看不到预期的崩溃。我的问题是:调用是否违反了C++标准SomeFooPtr->bar()
where SomeFooPtr == NULL
?
在我看来,这可能不是因为用户定义的operator->返回一个指针,这意味着即使该指针为NULL,它也肯定没有被取消引用(我确信取消引用NULL指针被标准视为非法或未定义)。另一方面,原始指针的语义不一定必须与用户定义的指针的语义相匹配——也许它们上的operator->被认为是取消引用,即使编译器不会生成一个。
这可能适用于大多数系统,但它是未定义的行为。引用标准:
5.2.5.3
If E1
具有类型“指向类 X 的指针”,则表达式E1->E2
转换为等效形式(*(E1)).E2
[...]
And:
5.2.5.1
A postfix expression followed by a dot .
or an arrow ->
, optionally followed by the keyword template
(14.8.1), and then followed by an id-expression, is a postfix expression. The postfix expression before the dot or arrow is evaluated;58) [...]
58) This evaluation happens even if the result is unnecessary to determine the value of the entire postfix expression, for example if the id-expression denotes a static member.
评估*x
where x
空指针会导致未定义的行为,因此在输入函数之前,您的情况显然是 UB 的情况。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)