First, we have to define a Closeable/Disposable public interface:
#include <iostream>
using namespace std;
class Disposable{
private:
int disposed=0;
public:
int notDisposed(){
return !disposed;
}
void doDispose(){
disposed = true;
dispose();
}
virtual void dispose(){}
};
Then we should define a macro for the using keyword:
#define using(obj) for(Disposable *__tmpPtr=obj;__tmpPtr->notDisposed();__tmpPtr->doDispose())
and; here is an example application:
class Connection : public Disposable {
private:
Connection *previous=nullptr;
public:
static Connection *instance;
Connection(){
previous=instance;
instance=this;
}
void dispose(){
delete instance;
instance = previous;
}
};
Connection *Connection::instance = nullptr;
int Execute(const char* query){
if(Connection::instance == nullptr){
cout << "------- No Connection -------" << endl;
cout << query << endl;
cout << "------------------------------" << endl;
cout << endl;
return -1;//throw some Exception
}
cout << "------ Execution Result ------" << endl;
cout << query << endl;
cout << "------------------------------" << endl;
cout << endl;
return 0;
}
int main(int argc, const char * argv[]) {
using(new Connection())
{
Execute("SELECT King FROM goats");//in the scope
}
Execute("SELECT * FROM goats");//out of the scope
}
But if you want to delete variables automatically from memory, you can simply use braces {}
; therefore, every variable inside of the scope will be removed at the end of the scope.
here is an example:
int main(int argc, const char * argv[]) {
{
int i=23;
}
// the variable i has been deleted from the momery at here.
}