QT 应用程序中 exc_bad_access 崩溃
我正在编写一个 QT 应用程序,但我对 C++ 非常生疏,所以我猜这就是问题所在。我的 Mac 上出现了 exc_bad_access
信号崩溃的情况,这意味着我的内存出现了问题。这是我的代码:
void MainWindowController::showMainWindow() {
MainWindow *w = mainWindow();
w ->show();
}
MainWindow *MainWindowController::mainWindow() {
if (NULL != _mainWindow)
return _mainWindow;
// otherwise, we need to load it and return it
_mainWindow = new MainWindow(0);
return _mainWindow;
}
_mainWindow
是一个实例变量,一个指针(您可能已经从函数签名中猜到了)。这是一个简单的延迟加载。我认为我的内存管理做得很好,因为这个类拥有该对象(稍后在析构函数中删除)。
崩溃发生在 w -> show();
行,QT 抱怨它在 QWidget show() 函数内的某处,这对我来说并没有真正的意义。
有人可以帮我吗?谢谢!
I'm writing a QT app and I'm very rusty with C++, so I'm guessing that's the problem. I've got a crash with an exc_bad_access
signal on my Mac, which means I'm doing something wrong with memory. Here's my code:
void MainWindowController::showMainWindow() {
MainWindow *w = mainWindow();
w ->show();
}
MainWindow *MainWindowController::mainWindow() {
if (NULL != _mainWindow)
return _mainWindow;
// otherwise, we need to load it and return it
_mainWindow = new MainWindow(0);
return _mainWindow;
}
_mainWindow
is an instance variable, a pointer (as you might have guessed from the function signature). It's a simple lazy-loading. I think I'm doing memory management OK, as this class owns the object (which is later deleted in the destructor).
The crash occurs on the w -> show();
line, QT complains its somewhere inside the QWidget show() function, which doesn't really make sense to me.
Can somebody help me out? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
事实证明,事情甚至更简单。我习惯了 Objective-C,其中 ivars 自动初始化为 0。C++ 不这样做。因此,我必须确保 _mainWindow 在构造函数中初始化为 NULL。问题解决了。
Turns out it was something even simpler. I'm used to Objective-C, where ivars are automatically initialized to 0. C++ doesn't do this. So, I had to make sure
_mainWindow
was initialized to NULL in the constructor. Problem solved.