如果多个线程共享一个指向同一个对象的指针,那么调用它的虚方法是否安全?当然我们应该假设方法本身是线程安全的。
class Base {
public:
virtual int test(int arg) = 0;
};
class Derived1: public Base {
public:
virtual int test(int arg) { return arg * 2; }
};
class Derived2: public Base {
public:
virtual int test(int arg) { return arg * 3; }
};
//call in threads:
Base* base = (pointer to the same Derived1);
int value = base->test(1);