当指针悬空时,这里出现了一个问题,询问“为什么这有效”。答案是它是 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 吗?