开发者

Ways to call a function on return

开发者 https://www.devze.com 2023-02-10 01:53 出处:网络
Whenever I have 2 specific functions, one that I want called upon entry of a function, and one that I want called upon return in a function, I usually use a helper class and put the functions that I w

Whenever I have 2 specific functions, one that I want called upon entry of a function, and one that I want called upon return in a function, I usually use a helper class and put the functions that I want called in the constructor and destructor - then just instantiate an object of that class at the beginning of a function. I do this mostly because I don't know how I would avoid placing the function that I want called on return everywhere before a return statement.

I was wondering if there are any alternative, or nicer methods to handling this problem. I am inexperienced, so I don't even know if my method is considered "terrible programmin开发者_如何学JAVAg" or not.


This is a fairly common technique. More specifically, the destructor will be called when leaving the scope where the object was initialized, which might be before the function returns. One use of this is with locks, where a helper object is used to do the unlock when it is destroyed.

This is the only way to ensure a function is called in all situations when leaving a scope, including when exceptions are thrown.

One different situation is where you want to instrument your code, which is what profilers (for example) do, which lets you hook into the code without actually calling anything explicitly. But I don't think this is what you're after.


This is the standard C++ way to do this. In early C with Classes there used to be a specific feature to specify functions called automatically on entry and exit of various functions, but they were removed in favor of using objects for this approach.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号