Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

前端 未结 16 1565
情深已故
情深已故 2020-11-22 17:15

Does C++ support \'finally\' blocks?

What is the RAII idiom?

What is the difference between C++\'s RAII idiom and C#\'s \'using\' statement?

16条回答
  •  一生所求
    2020-11-22 17:30

    As many people have stated, the solution is to use C++11 features to avoid finally blocks. One of the features is unique_ptr.

    Here is Mephane's answer written using RAII patterns.

    #include 
    #include 
    #include 
    using namespace std;
    
    class Foo
    {
     ...
    };
    
    void DoStuff(vector input)
    {
        list > myList;
    
        for (int i = 0; i < input.size(); ++i)
        {
          myList.push_back(unique_ptr(new Foo(input[i])));
        }
    
        DoSomeStuff(myList);
    }
    

    Some more introduction to using unique_ptr with C++ Standard Library containers is here

提交回复
热议问题