【发布时间】:2018-08-19 04:29:42
【问题描述】:
当指针悬空时,这里出现了一个问题,询问“为什么这有效”。答案是它是 UB,这意味着它可能有效,也可能无效。
我在一个教程中了解到:
#include <iostream>
struct Foo
{
int member;
void function() { std::cout << "hello";}
};
int main()
{
Foo* fooObj = nullptr;
fooObj->member = 5; // This will cause a read access violation but...
fooObj->function(); // Because this doesn't refer to any memory specific to
// the Foo object, and doesn't touch any of its members
// It will work.
}
这是否相当于:
static void function(Foo* fooObj) // Foo* essentially being the "this" pointer
{
std::cout << "Hello";
// Foo pointer, even though dangling or null, isn't touched. And so should
// run fine.
}
我错了吗?即使正如我解释的那样只是调用一个函数而不访问无效的 Foo 指针,它是 UB 吗?
【问题讨论】:
-
这是一个充满争议的话题。可能重复的示例:stackoverflow.com/a/28483256/560648stackoverflow.com/q/3498444/560648stackoverflow.com/q/5248877/560648 这些问题主要集中在访问静态成员上,但访问 no 成员最终是同一个问题
-
@Lightness Races in Orbit 那么我是否应该假设没有人知道真正的答案但我不应该玩火?
-
没有真正的答案,它是未定义的,您不可能尝试将特定行为与未定义行为联系起来。
-
@Zebra:我个人认为你可以放心地认为这是 UB,但这将是一个合理的后备位置是的
-
@SombreroChicken:它是否有UB(表面上)并不完全清楚;这就是重点
标签: c++ pointers undefined-behavior dangling-pointer