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?
Although you’ve shown the implementation of
util::getDBConnection, it doesn’t really answer the question, which is whether what it returns is ultimately a pointer that was allocated withnew.If it was, then an error message when you attempt to delete that pointer indicates that your heap has probably gotten corrupted (quite possibly in some completely unrelated code).
If it’s returning something that wasn’t allocated with
new, then the problem is even simpler — sinceauto_ptrusesdeleteon the pointer, it can only be used with something that was allocated withnew. Using it on a pointer that was allocated any other way will give UB.