Run Code Before Every Function Call for a Class in C++

后端 未结 9 1234
被撕碎了的回忆
被撕碎了的回忆 2021-02-15 13:08

I would like to run some code (perhaps a function) right before every function call for a class and all functions of the classes that inherit from that class. I\'d like to do t

相关标签:
9条回答
  • 2021-02-15 13:15

    Using g++, you could use the option -pg for the respective compilation units, which makes the compiler generate a call to the function mcount at the start of every function. mcount is usually provided by profiling tools like gprof, but you can also implement it yourself. You should however make sure that

    • mcount has C linkage (and is not C++-style name-mangled), i.e. by implementing it as a C function and compiling with a pure C compiler like gcc.
    • the compilation unit containing mcount is not compiled with -pg.
    0 讨论(0)
  • 2021-02-15 13:18

    Another thing you could consider is using something like the [boost/C++0X] shared_ptr wrapper, where you call your custom function on the '->' overload before returning the class instance pointer. It involves modifying usage but not the underlying class, and I've used it a couple times to achieve the same effect. Just another thought.

    0 讨论(0)
  • 2021-02-15 13:23

    I would suggest using the Non Virtual Interface idiom. All public functions are non-virtual. All virtual functions are protected or private. Public members delegate the calls to virtual members and are usually implemented as inline functions.

    This is the way IOStreams are implemented in STL. You can read more about it at C++ Wikibooks.

    Intent: To modularize/refactor common before and after code fragments (e.g., invariant checking, acquiring/releasing locks) for an entire class hierarchy at one location.

    Regards,
    Ovanes

    0 讨论(0)
  • 2021-02-15 13:27

    The following might be a bit of an overkill - but how about?

    http://msdn.microsoft.com/en-us/library/c63a9b7h.aspx

    0 讨论(0)
  • 2021-02-15 13:28

    This sounds like what a profiler does. Have you looked at the source for any profiling tools?

    0 讨论(0)
  • 2021-02-15 13:29

    You could also do this with the Curiously recurring template pattern (CRTP).

    0 讨论(0)
提交回复
热议问题