Я не понимаю, почему моя программа выходит из строя, может быть, вы заметите это.
typedef boost::shared_ptr < std::string > StringPtr;
typedef std::pair < HWND, StringPtr > WMapPair;
typedef std::map < HWND, StringPtr > WindowMap;
// this callback populates the WindowMap (m_Windows) by adding a WMapPair each time
BOOL CALLBACK EnumWindowsCallback( HWND hWnd )
{
// adds this window to the WindowMap, along with its title text
BOOL bRetVal = FALSE;
int nTextLen = 0;
char* sWindowText = NULL;
if( ! ::IsWindow( hWnd ) )
return FALSE;
nTextLen = GetWindowTextLength( hWnd );
if( ! nTextLen )
return TRUE;
sWindowText = new char[nTextLen + 1];
if( sWindowText )
{
GetWindowTextA( hWnd, sWindowText, nTextLen );
m_Windows.insert( WMapPair(hWnd, StringPtr(new std::string(sWindowText))) );
delete [] sWindowText;
sWindowText = NULL;
bRetVal = TRUE;
}
return bRetVal;
}
Мой класс, содержащий эту совокупность WindowMap, работает правильно, но разборка, похоже, работает некорректно. Деструктор класса вызывает эту функцию, чтобы очистить карту - которая должна освободить shared_ptr, тем самым удалив их, верно? :)
void EraseList()
{
m_Windows.clear();
}
Я хотел бы знать, что мне не хватает - все StringPtr протекают.
UPDATE RE комментарий о том, что "StringPtr (new std :: string (sWindowText)))" был стилистически неверно, я сделал предложенное изменение, как показано ниже, но утечка памяти все еще существует.
BOOL CALLBACK EnumWindowsCallback( HWND hWnd )
{
// adds this window to the WindowMap, along with its title text
BOOL bRetVal = FALSE;
int nTextLen = 0;
char* sWindowText = NULL;
StringPtr strPtr;
if( ! ::IsWindow( hWnd ) )
return FALSE;
nTextLen = GetWindowTextLength( hWnd );
if( ! nTextLen )
return TRUE;
sWindowText = new char[nTextLen + 1];
if( sWindowText )
{
GetWindowTextA( hWnd, sWindowText, nTextLen );
strPtr = StringPtr(new std::string(sWindowText));
m_Windows.insert( WMapPair(hWnd, strPtr) );
delete [] sWindowText;
sWindowText = NULL;
bRetVal = TRUE;
}
return bRetVal;
}
Заключение Я предложил отказаться от StringPtr и использовать make_pair (hWnd, std :: string () ) и таким образом обошли проблему.