【发布时间】:2014-06-19 11:53:53
【问题描述】:
基于C++ polymorphism with variadic function parameter我尝试编写类似的(非模板化,带构造函数)程序
代码:
#include <thread>
#include <iostream>
#include <vector>
class Base
{
public:
Base (int count) { run(count); } // this-> does not help
virtual void run (int count) { // non-virtual does not help eighter
for (int i=0; i<count; ++i)
threads.emplace_back(std::ref(*this));
}
virtual ~Base () {
for (auto& t : threads)
t.join();
}
virtual void operator() () = 0;
protected:
std::vector< std::thread > threads;
};
class Derived : public Base
{
public:
using Base::Base;
virtual void operator() () { std::cout << "d"; }
};
int main()
{
Derived d(4);
std::cout << std::endl;
return 0;
}
预期结果:
dddd
真实结果(Ubuntu 14.04,gcc v4.8.2):
pure virtual method called
pure virtual method called
terminate called without an active exception
terminate called without an active exception
dAborted (core dumped)
请注意,Derived::operator() 至少被真正调用过一次(d 在最后一行,几乎总是如此)。
即使代码非常简单并且与原始代码几乎相同(参见上面的链接),它也不起作用。我花了好几个小时来解决这个问题。
目标是用多个线程构造Derived。这个数量的线程将被执行(在构造函数中)并在析构函数中加入。 operator() 应该用作线程体函数(如在原始代码中)。此外,为了提供多态性,它应该是虚拟的。
就我而言,run 传递 *this(出于某种原因)键入为 Base,而不是 Derived,因此线程执行 Base::operator(),这是纯虚拟的
附加问题:有没有办法标记operator()受保护?
谁能帮帮我?谢谢。
编辑:
根据Billy ONeal的回答我重写了代码,所以Derived构造函数调用了run,但是没有任何成功
#include <thread>
#include <iostream>
#include <vector>
class Base
{
public:
virtual void run (int count) { // non-virtual does not help eighter
for (int i=0; i<count; ++i)
threads.emplace_back(std::ref(*this));
}
virtual ~Base () {
for (auto& t : threads)
t.join();
}
virtual void operator() () = 0;
protected:
std::vector< std::thread > threads;
};
class Derived : public Base
{
public:
Derived (int count) { run(count); }
virtual void operator() () { std::cout << "d"; }
};
int main()
{
Derived d(4);
std::cout << std::endl;
return 0;
}
结果会随时间而变化 - 这就是我得到的所有结果
1) d
2) dd
3) ddd
4) dddd
5) d
pure virtual method called
terminate called without an active exception
ddAborted (core dumped)
尤其是5)我无法解释。
我在 Derived d(4); 周围添加了 {...} 作为匿名块,以强制在行结束程序终止的 endl 之前执行析构函数,但因为我只有
pure virtual method called
terminate called without an active exception
ddAborted (core dumped)
【问题讨论】:
-
我不认为代码是一样的。
-
好吧,我想这很相似..
标签: c++ multithreading c++11 polymorphism pure-virtual