每当我输出特定的指针地址时std::cout
,我都会崩溃:
bool MyClass::foo() const
{
std::cout << "this prints fine" << std::endl << std::flush;
std::cout << d << std::endl << std::flush; // crash!
return true;
}
Run Code Online (Sandbox Code Playgroud)
哪里d
是类的指针成员,即:
class MyClass {
// ...
private:
MyClassPrivate* d;
};
Run Code Online (Sandbox Code Playgroud)
什么可能导致应用程序崩溃?即使它是一个 NULL 指针,或者一个初始化的指针,它仍然应该打印出(可能是无效的)地址,对吗?
如果有影响的话,应用程序会在调试模式下编译。该函数foo
未标记为内联。
背景:我正在尝试追踪外部应用程序流程中的错误。仅当另一个应用程序向进程发送快速命令时才会导致该错误。我用来std::cout
跟踪外部进程的执行。
如果this
不是有效的指针,则对成员字段的任何访问都可能导致访问冲突。在无效指针上调用的非虚拟方法在尝试访问字段之前可以正常工作,因为调用本身不需要取消引用this
。
例如,这种情况会大致像您所描述的那样崩溃:
MyClass* instance = nullptr; // or NULL if you're not using C++11
instance->foo(); // will crash when `foo` tries to access `this->d`
Run Code Online (Sandbox Code Playgroud)