Given a code below
class Base {
public:
virtual void callThisOnce();
};
class Derived_A: public Base {};
class Derived_B: public Base {};
void function(std::vector<shared_ptr<Base>> v) {
for (auto i : v)
i->callThisOnce();
}
Vector v
contains either or both shared_ptr<Derived_A>
and shared_ptr<Derived_B>
objects.
What I want to archive is that when ever function
is called, if in v
there is a object belong to class Derived_A
, Derived_A::callThisOnce
should be executed once; and if there is a object belong to class Derived_B
, Derived_B::callThisOnce
should be executed once.
I need a coding pattern that make it easiest to create Derived_C
.
I tried this
class Derived_A: public Base {
virtual void callThisOnce(){
if(!_mutex.try_lock())
return;
/* Do something */
}
static std::mutex _mutex;
};
void function(std::vector<shared_ptr<Base>> v) {
for (auto i : v)
i->callThisOnce();
Derived_A::_mutex.try_lock(); // this call prevent undefined behavior of mutex::unlock
Derived_A::_mutex.unlock();
}
This pattern make me create a static mutex an required me to call std::mutex::unlock
of all class. But it's seem to leave many problems.
Is there a better method to archive the same?