Re: What's wrong with this class
Victor Bazarov wrote:
John Doe wrote:
So here is the update code (without the try for new I will do it later)
but now I get an error :
error C2662: 'NetworkList::Clear' : cannot convert 'this' pointer from
'const NetworkList' to 'NetworkList &'
so I have added const to Clear()...
//============================================//
// NetworkManager.h
//============================================//
struct DeletePointer {
template<typename T>
void operator()(const T* ptr) const
{
delete ptr;
}
};
class Network
{
public:
Network() {};
Network(CString const& netName, GUID netguid):
_netname(netName), _netguid(netguid) {}
~Network() {}
CString const& getName() { return _netname; }
GUID getGuid() const { return _netguid; }
private:
CString _netname;
GUID _netguid;
};
class NetworkList
{
typedef std::list<Network*>::iterator NetworkListIt;
public:
NetworkList()
{
}
~NetworkList()
{
Clear();
}
void Clear()
{
for_each( _netlist.begin(), _netlist.end(), DeletePointer ());
}
void Add(Network* network)
{
if (network)
_netlist.push_back(network);
}
const Network* getNetwork(CString const& netNameOrGuid) const
{
if ((netNameOrGuid.GetAt(0) == '{') &&
netNameOrGuid.GetLength() == 39)
{
CLSID guid;
if (SUCCEEDED(CLSIDFromString((LPOLESTR)(LPCTSTR)netNameOrGuid,&guid)))
{
return getNetwork(guid);
}
}
else
{
std::list<Network*>::const_iterator it;
//NetworkListIt it;
for (it = _netlist.begin(); it != _netlist.end(); ++it)
if (!(*it)->getName().CompareNoCase(netNameOrGuid))
return (*it);
}
return NULL;
}
const Network* getNetwork(CLSID guid) const
{
if (!_netlist.empty())
Clear();
std::list<Network*>::const_iterator it;
//NetworkListIt it;
for (it = _netlist.begin(); it != _netlist.end(); ++it)
if ((*it)->getGuid() == guid)
return (*it);
return NULL;
}
private:
std::list<Network*> _netlist;
};
//============================================//
// NetworkManager.cpp
//============================================//
NetworkList getNetworkList()
{
NetworkList netList;
// Simulate we retrieve network list from OS
GUID guid;
netList.Add(new Network(_T("Network1"), guid));
netList.Add(new Network(_T("Network2"), guid));
return netList;
}
//============================================//
// Testcase
//============================================//
void OnGettingNetworkList()
{
NetworkList netList = getNetworkList();
}
When the netList is destroyed I get a debug assertion due to CString
object :
void Release() throw()
{
ATLASSERT( nRefs != 0 ); <<<<< !!!!!!!!!
if( _AtlInterlockedDecrement( &nRefs ) <= 0 )
{
pStringMgr->Free( this );
}
}