在下面的節目,我有一個虛擬的呼叫從一個線程中:虛擬呼叫忽略派生
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
class A {
public:
virtual ~A() { t.join(); }
virtual void getname() { std::cout << "I am A.\n"; }
void printname()
{
std::unique_lock<std::mutex> lock{mtx};
cv.wait(lock, [this]() {return ready_to_print; });
getname();
};
void set_ready() { std::lock_guard<std::mutex> lock{mtx}; ready_to_print = true; cv.notify_one(); }
void go() { t = std::thread{&A::printname,this}; };
bool ready_to_print{false};
std::condition_variable cv;
std::mutex mtx;
std::thread t{&A::printname,this};
};
class B : public A {
public:
int x{4};
};
class C : public B {
void getname() override { std::cout << "I am C.\n"; }
};
int main()
{
C c;
A* a{&c};
a->getname();
a->set_ready();
}
我希望該程序將打印:
I am C.
I am C.
I am C.
I am A.
在程序中,我等到派生對象完全構造,然後再調用t他虛擬的成員函數。但是線程在對象完全構建之前啓動。
如何保證虛擬電話?
你用什麼平臺? VS2015U3 - 「我是C」是預期的兩倍。 –
在問題中的鏈接中使用了clang,但我[與gcc相同](http://coliru.stacked-crooked.com/a/688e7d3c5107e57a)。同樣,使用'Microsoft Visual Studio Community 2015版本14.0.25431.01 Update 3',我也可以得到同樣的結果。但是如果我在VS2015的調試模式下單步執行,那麼我會得到兩次「我是C」。 – wally
嗯,這是奇怪的。我有'Microsoft Visual Studio Professional 2015版本14.0.25431.01 Update 3'。適用於調試和發佈。 –