将基类的引用传递给 boost::thread 并在派生类中调用虚函数是否有效
Will it work to pass a reference to a base class to boost::thread, and have virtual functions in the derived class called?
假设我有:
class Base
{
public:
void operator()()
{
this->run();
}
virtual void run () {}
}
class Derived : public Base
{
public:
virtual void run ()
{
// Will this be called when the boost::thread runs?
}
}
int main()
{
Base * b = new Derived();
boost::thread t(*b); // <-- which "run()" function will be called - Base or Derived?
t.join();
delete b;
}
从我的测试来看,我无法Derived::run()
被召唤。 是我做错了什么,还是这是不可能的?
通过传递*b
,您实际上Derived
对象"切片",即按值传递Base
实例。您应该通过指针(或智能指针)传递Derived
函子,如下所示:
thread t(&Derived::operator(), b); // boost::bind is used here implicitly
当然,要注意b
寿命。
@GManNickG的评论是最干净的答案,并且非常有效。 Boost.Ref是要走的路。
thread t(boost::ref(*b));
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 调用派生类成员函数
- 从基类实例调用派生类方法而不进行强制转换
- 从基类 (C++) 调用派生类中的非虚函数
- 在将派生类指针类型转换为派生类指针后,从基类指针调用派生类函数
- 如何从 Gtk::窗口调用派生对象的析构函数
- 在dynamic_pointer_cast后调用派生类的构造函数
- 从 Base 引用对象调用派生类的成员
- 有没有办法在没有虚拟的情况下使用基类指针调用派生类函数
- 在 c++ 中,如何使用向量调用派生类?
- C++通过 const 引用传递时不调用派生类函数
- 哪个基类调用派生重写的方法?
- 如何从包含基类指针的容器中调用派生类函数(基于其类型)?
- 如何调用派生类之一
- 从基类数组调用派生函数
- 从具有泛型返回类型的 crtp 基类调用派生类中的函数
- 基类如何调用派生类在 c++ 中传递的闭包?
- 通过在基类中虚拟调用派生类中的函数来访问派生类中的函数
- 如何在另一个类的向量中调用派生类的析构函数
- 通过reinterpret_casting方法指针从指针调用派生类的方法。这是 UB 吗?