Tuesday, 15 February 2011

c++ - Something like a nested mutex but more generic? -



c++ - Something like a nested mutex but more generic? -

i working on project file must saved after operations have been performed on class's fellow member objects. want save file after 1 operation, need not save until after batch of operations have been performed.

my thought utilize class works recursive mutex. except instead of locking , unlocking mutex, want class phone call method (in case, save file) when lastly instance of class in stack falls out of scope.

implementing class not problem, feels generic problem can't find in boost or stl. there pre-existing standard solution problem, or need roll own class it? if so, approach right one, or there improve way solve problem?

below simple implementation of kind of behavior looking for. print "hello world!" twice though doitonce() beingness called 11 times. utilize genericguard pulling recognized standard rather sticking own implementation in code base. possible?

#include <iostream> void noop (void) { } void helloworld (void) { std::cout << "hello world!" << std::endl; } // imagine generic implementation like... template <void (*initfunc)(), void (*destructfunc)()> class genericguard { int & _i; public: genericguard (int & i) : _i(i) { if (_i++ == 0) { initfunc(); } } ~genericguard () { if (--_i == 0) { destructfunc(); } } }; int helloworldcounter; // utilize mill class in real-world? typedef genericguard<noop, helloworld> helloworldguard; void dosomethingonce (void) { helloworldguard g (helloworldcounter); // } void doittentimes (void) { helloworldguard g (helloworldcounter); (int = 0; < 10; ++i) { dosomethingonce(); } } int main (void) { dosomethingonce(); doittentimes(); homecoming 0; }

you can utilize shared_ptr custom deleter function.

stl (since c++11): http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr boost: http://www.boost.org/doc/libs/1_55_0/libs/smart_ptr/shared_ptr.htm#deleter_constructor

example :

#include <memory> #include <iostream> void helloworld(void *) { std::cout << "hello world!" << std::endl; } class mill { public: static std::shared_ptr<void> get_instance() { static std::weak_ptr<void> ref; if (ref.expired()) { std::shared_ptr<void> sp{nullptr, helloworld}; ref = sp; homecoming sp; } homecoming ref.lock(); } }; void dosomethingonce (void) { std::shared_ptr<void> g = factory::get_instance(); // } void doittentimes (void) { std::shared_ptr<void> g = factory::get_instance(); (int = 0; < 10; ++i) { dosomethingonce(); } } int main(void) { dosomethingonce(); doittentimes(); homecoming 0; }

c++ boost stl

No comments:

Post a Comment