Search code examples
c#c++templatesusing-statement

Implementing C++ equivalent of C# using statement


I am looking for an elegant solution for implementing the equivalent of the C# using statement in C++. Ideally the resultant syntax should be simple to use and read.

C# Using statement details are here - http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.80).aspx

I am not sure whether the solution would be to use function pointers with destructors on classes, some form of clever template programming or even meta template programming. Basically I do not know where to start with this...


Solution

  • 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.