It's a bit similar to a smart pointer.
Of course, this is a template class that you can use for any pointer you want to manage.
// Function object used to delete the MySQL result set
Struct mysql_result_deleter
{
Void operator () (mysql_res * result)
{
If (result! = NULL)
Mysql_free_result (result );
}
};
// Delete the resource policy by default.
Template <class _ ty>
Struct my_default_delete
{// Default deleter for unique_ptr
Typedef my_default_delete <_ ty> _ MYT;
My_default_delete ()
{// Default construct
}
Template <class _ ty2>
My_default_delete (const my_default_delete <_ ty2> &)
{// Construct from another default_delete
}
Void operator () (_ ty * _ PTR) const
{// Delete a pointer
If (0 <sizeof (_ ty) // won't compile for incomplete type
Delete _ PTR;
}
};
// This class is as simple as possbile to hold the stack pointers
// To make sure that the pointer will be deleted if there is any exception
//
// Template Function
Template <typename T1, typename t2 = my_default_delete <t1>
Class scope_ptr_holder
{
T1 * original_pointer;
T2 itsdeleter;
Public:
Explicit scope_ptr_holder (T1 * t) // Constructor
: Original_pointer (t ){}
Explicit scope_ptr_holder (T1 * t, T2 deleter) // Constructor
: Original_pointer (t ),
Itsdeleter (deleter ){}
Void reset (T1 * newptr)
{
If (newptr = original_pointer)
Return;
If (original_pointer! = NULL)
Itsdeleter (original_pointer );
Original_pointer = newptr;
}
~ Scope_ptr_holder ()
{
If (original_pointer! = NULL)
{
Itsdeleter (original_pointer );
Original_pointer = NULL;
}
}
Protected:
Scope_ptr_holder (const scope_ptr_holder &);
Const scope_ptr_holder & operator = (const scope_ptr_holder &);
};
}
Instance code:
Sqlstream <"select * From pagecontainequipment where pageid =" <page-> GETID () <Endl;
String SQL = sqlstream. STR ();
Mysql_res * result = queryandreturnresult (SQL. c_str ());
If (result = NULL)
Return false;
Scope_ptr_holder <mysql_res, mysql_result_deleter> resultholder (result );
The Code has been used in the actual project, so there is no problem.