I'm new to C++ and a bit confused regarding auto_ptr.
I have a class which inside has a static auto_ptr.
static std::auto_ptr<MyCompany::CConnection> con = std::auto_ptr<MyCompany::CConnection> (util::getDBConnection() );
Util::getDBConnection() implementation :
CConnection* util::getDBConnection(){
try
{
cout<< &MyCompany::GetFermatConnection();
return &MyCompany::GetFermatConnection();
}
catch(...)
{
//connect to local DB
throw;
}
}
However when my program finished, it always hit an exception in memory, during the destructor of auto pointer.
~auto_ptr()
{ // destroy the object
if (_Myptr != 0)
delete _Myptr; // exception in this line.
}
The exception is "Unhandled exception at 0x00000001800024e8 in TestDLL.exe: 0xC0000005: Access violation reading location 0xffffffffffffffff."
I understand that auto_ptr will try release any memory when it reach the end of its scope. But, in this case I don't have any idea what goes wrong. Does anyone know what is the possible cause?
auto_ptrinitialized correctly? Can you put a break point in theutil::getDBConnection()and see what it returns?util::getDBConnection()returns -1 by anychance ?auto_ptris probably not what you want, as it does not really offer any lifetime management at all. It will only get destroyed at the very end of the program, a case for which you don't need anauto_ptrin the first place. The only place where this could be useful is when using custom deleters but that does not seem to be the case here.getDBConnectionit looks the memory forDBConnectionis not allocated usingnew.