Implementing C++ equivalent of C# using statement
You don't need to implement this in C++ because the standard pattern of RAII already does what you need.
{
ofstream myfile;
myfile.open("hello.txt");
myfile << "Hello\n";
}
When the block scope ends, myfile
is destroyed which closes the file and frees any resources associated with the object.
The reason the using
statement exists in C# is to provide some syntactic sugar around try/finally and IDisposable
. It is simply not needed in C++ because the two languages differ and the problem is solved differently in each language.
I'd take a look at using std::auto_ptr<> to handle cleanup of any instances allocated and assigned to a pointer within a particular scope -- otherwise, any variables declared within a specific scope will simply be destructed when exiting said scope.
{
SomeClass A;
A.doSomething();
} // The destructor for A gets called after exiting this scope here
{
SomeClass* pA = new SomeClass();
std::auto_ptr<SomeClass> pAutoA(pA);
pAutoA->doSomething();
} // The destructor for A also gets called here, but only because we
// declared a std::auto_ptr<> and assigned A to it within the scope.
See http://en.wikipedia.org/wiki/Auto_ptr for a little more information on std::auto_ptr<>
A more verbose RAII pattern that resembles C#'s using statement can be accomplished with a simple macro.
#define Using(what, body) { what; body; }
Using(int a=9,
{
a++;
})
a++; // compile error, a has gone out of scope here
Note we must use a capital "Using" to avoid a collision with C++'s built in "using" statement which obviously has a different meaning.