受到the other topic的启发,我编写了这个模拟finally
块的代码:
#include <cassert>
#include <iostream>
struct base { virtual ~base(){} };
template<typename TLambda>
struct exec : base
{
TLambda lambda;
exec(TLambda l) : lambda(l){}
~exec() { lambda(); }
};
class lambda{
base *pbase;
public:
template<typename TLambda>
lambda(TLambda l): pbase(new exec<TLambda>(l)){}
~lambda() { delete pbase; }
};
class A{
int a;
public:
void start(){
int a=1;
lambda finally = [&]{a=2; std::cout<<"finally executed";};
try{
assert(a==1);
//do stuff
}
catch(int){
//do stuff
}
}
};
int main() {
A a;
a.start();
}
输出(ideone):
finally executed
@Johannes似乎认为它不完全正确,commented that:
如果编译器没有,它可能会崩溃 在临时副本中删除 初始化,因为它 使用相同的指针删除两次 值
我想知道究竟是怎么回事。帮助我理解问题: - )
编辑:
问题修复为:
class lambda{
base *pbase;
public:
template<typename TLambda>
lambda(TLambda l): pbase(new exec<TLambda>(l)){}
~lambda() { delete pbase; }
lambda(const lambda&)= delete; //disable copy ctor
lambda& operator=(const lambda&)= delete; //disable copy assignment
};
然后将其用作:
//direct initialization, no copy-initialization
lambda finally([&]{a=2; std::cout << "finally executed" << std::endl; });
答案 0 :(得分:8)
在此初始化中:
lambda finally = [&]{a=2; std::cout<<"finally executed";};
可以使用lambda
隐式定义的复制构造函数。这只会复制原始指针pbase
,然后将被删除多次。
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)
实际上,你的断言触发掩盖了双重删除问题,但这证明了我突出显示的崩溃。
$ g++ -std=c++0x -Wall -Wextra -pedantic -fno-elide-constructors -DNDEBUG lambdafun.cc
$ ./a.out
Segmentation fault (core dumped)
答案 1 :(得分:2)
似乎比必要的方式更复杂。为什么不呢:
class finally
{
std::function<void (void)> const action;
finally(const finally&) = delete;
public:
finally(std::function<void (void)> a)
: action(a)
{}
~finally() { action(); }
};
但总的来说,人们应该尽量不要将糟糕的Java习惯带入C ++。