call function when leaving scope

后端 未结 2 755
栀梦
栀梦 2021-01-23 04:27

What is the most elegant solution for calling a function automatically when leaving a scope? My current approach (see below) works but I guess there should be something more gen

2条回答
  •  无人共我
    2021-01-23 04:35

    Using a constructor/destructor in this way is a common way to solve this sort problem. I have used it for both locks (constructor takes lock, destructor releases it) and logging purposes (constructor prints something on construction, and destructor prints on destruction, giving a nice callgraph of a project - in the latter case, using macros to also get __FILE__ and __LINE__ store in the object, so we can see where the constructor was called [it's almost impossible to do this for the destructor, but typically it's possible to see the constructor and make out where the destructor gets called]).

提交回复
热议问题