嵌套类引发vector容器元素为空
TCHAR* pstr = NULL;
while (...)
{
CString strName = GetData();
ASSERT(!strName.IsEmpty());
pstr = new TCHAR[MAX_PATH];
lstrcpy(pstr, strName);
obj.m_vec.push_back(pstr);
}
循环后,结果容器发现为空,,一个元素都没有,非常奇怪。
上完整的code:
class Example
{
struct test
{
vector<TCHAR*> m_vec;
public:
~test()
{
for(vector<TCHAR*>::iterator iter = m_vec.begin(); iter != m_vec.end(); iter ++)
{
if( *iter != NULL)
{
delete *iter;
*iter = NULL;
}
}
}
}obj;
//其他成员函数省去
};
调用代码:
TCHAR* pstr = NULL;
while (...)
{
CString strName = GetData();
ASSERT(!strName.IsEmpty());
pstr = new TCHAR[MAX_PATH]; //肯定有值的
lstrcpy(pstr, strName);
obj.m_vec.push_back(pstr);
}
是不是嵌套类的导致的vector为空,一个元素都没有
[解决办法]
你的问题跟嵌套类没关系。
[解决办法]
嵌套类,一点也没有问题:
这里有一个VC MFC 控制台例子,如下:
#include "stdafx.h"
#include "CStingTest.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// The one and only application object
CWinApp theApp;
using namespace std;
void main_func()
{
class Example
{
public:
struct test{
public:
vector<TCHAR *> m_vec;
~ test(){
if(m_vec.size() ==0 )return ;
for(vector<TCHAR *> ::iterator it =m_vec.begin();it!=m_vec.end();it++)
{
_tprintf(_T("%s \n"),*it);
delete *it;
*it=NULL;
}
}
}test;
}obj;
int i=0;
while(i<10)
{
CString strName = _T("Abcd");//GetData();
ASSERT(!strName.IsEmpty());
CString s;
s.Format (_T(" %d") , i);
strName+= s;
TCHAR* pstr = new TCHAR[MAX_PATH];
//lstrcpy(pstr, (LPCTSTR)strName);//
_tcscpy(pstr, (LPCTSTR)strName);//_tcscpy 可能更好。
obj.test.m_vec.push_back(pstr);
i++;
}
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
CString strHello;
strHello.LoadString(IDS_HELLO);
cout << (LPCTSTR)strHello << endl;
main_func();
}
return nRetCode;
}