gpt4 book ai didi

c++ - 断言在 VS2008 但不是在 VS2005

转载 作者:行者123 更新时间:2023-11-30 02:13:14 25 4
gpt4 key购买 nike

从VS2005切换到VS2008 SP1后,发现一个无法解释的问题。
一个程序在 VS2005 下在发布和 Debug模式下运行良好。在 VS2008 下,当进入调试器时会引发断言。
如果我让程序运行(在调试或 Release模式下),则根本没有断言。

我在这上面花了将近两天的时间,但我不明白我做错了什么。

程序说明:我有一个基于 MFC 对话框的程序,它创建一个用户线程 (CWinThread),该线程创建应用程序的主对话框。
工作线程无限循环并每秒向对话框发布一条消息。消息在 gui 线程中处理。

我的部分代码:

gui线程的InitInstance:

BOOL CGraphicalThread::InitInstance()
{
CGUIThreadDlg* pDlg = new CGUIThreadDlg();
pDlg->Create(CGUIThreadDlg::IDD);
m_pMainWnd = pDlg;
AfxGetApp()->m_pMainWnd = pDlg;
return TRUE;
}

工作线程:

UINT ThreadProc(LPVOID pVoid)
{
do
{
AfxGetApp()->m_pMainWnd->PostMessage(WM_APP+1, (WPARAM)new CString("Hello"), NULL);
Sleep(1000);
}
while(!bStopThread);

return 0;
}

对话消息处理程序是这样的:

LRESULT CGUIThreadDlg::OnMsg(WPARAM wp, LPARAM lp)
{
CListBox* pList = (CListBox*)GetDlgItem(IDC_LIST1);
CString* ps = (CString*)wp;
pList->InsertString(-1, *ps);
delete ps;
return 1L;
}

这在 VS2005 上工作得很好。但是对于 VS2008,一旦设置断点并进入 Debug模式,我就会引发一个断言 ???
wincore.cpp 第 906 行

CObject* p=NULL;
if(pMap)
{
ASSERT( (p = pMap->LookupPermanent(m_hWnd)) != NULL ||
(p = pMap->LookupTemporary(m_hWnd)) != NULL);
}
ASSERT((CWnd*)p == this); // must be us
// Note: if either of the above asserts fire and you are
// writing a multithreaded application, it is likely that
// you have passed a C++ object from one thread to another
// and have used that object in a way that was not intended.
// (only simple inline wrapper functions should be used)
//
// In general, CWnd objects should be passed by HWND from
// one thread to another. The receiving thread can wrap
// the HWND with a CWnd object by using CWnd::FromHandle.
//
// It is dangerous to pass C++ objects from one thread to
// another, unless the objects are designed to be used in
// such a manner.

如果我删除 GUI 线程并将对话框创建到 CWinApp 线程中,问题就不会再出现。

有人知道吗?
我做错了什么吗?

谢谢

最佳答案

// Note: if either of the above asserts fire and you are
// writing a multithreaded application, it is likely that
// you have passed a C++ object from one thread to another
// and have used that object in a way that was not intended.
// (only simple inline wrapper functions should be used)
//
// In general, CWnd objects should be passed by HWND from
// one thread to another. The receiving thread can wrap
// the HWND with a CWnd object by using CWnd::FromHandle.
//
// It is dangerous to pass C++ objects from one thread to
// another, unless the objects are designed to be used in
// such a manner.

关于c++ - 断言在 VS2008 但不是在 VS2005,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/701390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com