Simulating finally block in C++0x

自作多情 提交于 2019-12-04 09:50:59

In this initialization:

lambda finally = [&]{a=2; std::cout<<"finally executed";};

The implicitly defined copy constructor for lambda may be used. This will just copy the raw pointer pbase which will then be deleted more than once.

E.g.

$ g++ -std=c++0x -Wall -Wextra -pedantic -fno-elide-constructors lambdafun.cc 
$ ./a.out 
a.out: lambdafun.cc:29: void A::start(): Assertion `a==1' failed.
finally executedAborted (core dumped)

Actually, your assert firing masks the double delete problem, but this demonstrates the crash I was highlighting.

$ g++ -std=c++0x -Wall -Wextra -pedantic -fno-elide-constructors -DNDEBUG lambdafun.cc 
$ ./a.out 
Segmentation fault (core dumped)

Seems way more complicated than necessary. Why not just:

class finally
{
    std::function<void (void)> const action;
    finally(const finally&) = delete;

public:
    finally(std::function<void (void)> a)
        : action(a)
    {}

    ~finally() { action(); }
};

But in general, one should try not to carry bad Java habits over into C++.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!