什么可能导致写指针地址到std :: cout崩溃?
每当我输出特定的指针地址std::cout
,我得到一个崩溃:什么可能导致写指针地址到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;
}
哪里d
是类的指针成员,即:
class MyClass {
// ...
private:
MyClassPrivate* d;
};
什么会导致应用程序崩溃?即使它是一个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`
为了测试这个理论,添加'std :: cout
谢谢,这似乎是这样的:'std :: cout
有可能是operator<<(ostream &, MyClassPrivate*)
过载,即取消引用指针。例如,当然有MyClassPrivate
确实是char
。
尝试std::cout << (void*)d;
,看看它是否有所作为。如果没有,zneak的答案似乎是合理的。
也许你有operator killogre
你可以告诉崩溃是在'operator zneak
*旁白*:'std :: endl'已经执行了'std :: flush'。代码中的std :: flush是多余的。 –