有人能帮忙解释一下这种意外的行为吗?
前提条件
我创建了一个包含成员变量std :: thread
的Thread类。 Thread的构造函数构造成员std :: thread
,并提供一个指向静态函数的指针,该函数调用纯虚函数(由基类实现)。
代码
#include <iostream>
#include <thread>
#include <chrono>
namespace
{
class Thread
{
public:
Thread()
: mThread(ThreadStart, this)
{
std::cout << __PRETTY_FUNCTION__ << std::endl; // This line commented later in the question.
}
virtual ~Thread() { }
static void ThreadStart(void* pObj)
{
((Thread*)pObj)->Run();
}
void join()
{
mThread.join();
}
virtual void Run() = 0;
protected:
std::thread mThread;
};
class Verbose
{
public:
Verbose(int i) { std::cout << __PRETTY_FUNCTION__ << ": " << i << std::endl; }
~Verbose() { }
};
class A : public Thread
{
public:
A(int i)
: Thread()
, mV(i)
{ }
virtual ~A() { }
virtual void Run()
{
for (unsigned i = 0; i < 5; ++i)
{
std::cout << __PRETTY_FUNCTION__ << ": " << i << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
protected:
Verbose mV;
};
}
int main(int argc, char* argv[])
{
A a(42);
a.join();
return 0;
}
问题
你可能已经注意到了一个微妙的错误:在Thread
构造函数上下文中调用Thread::ThreadStart(...)
,因此调用纯虚函数/虚函数不会调用派生类的实现。这由运行时错误证明:
pure virtual method called
terminate called without an active exception
Aborted
然而,如果我在Thread
的构造函数中删除对std::cout
的调用,则会出现意外的运行时行为:
virtual void {anonymous}::A::Run(){anonymous}::Verbose::Verbose(int): : 042
virtual void {anonymous}::A::Run(): 1
virtual void {anonymous}::A::Run(): 2
virtual void {anonymous}::A::Run(): 3
virtual void {anonymous}::A::Run(): 4
例如,在Thread
的构造函数中删除对std::cout
的调用似乎会产生这样的效果:可以在基类构造函数上下文中调用派生类的纯虚/虚函数!这与之前的学习和经验不符。
在Windows 10上的Cygwin x64构建环境中,gcc版本为:
g++ (GCC) 5.4.0
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
我对这个观察结果感到困惑,对发生的事情非常好奇。有人可以解释一下吗?