Im folgenden Programm, das ich aus einem Thread einen virtuellen Aufruf haben:Virtuelles Call innerhalb Thread abgeleitet ignoriert Klasse
#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();
}
ich das Programm hatte gehofft, würde drucken:
I am C.
I am C.
Aber instead it prints:
I am C.
I am A.
Im Programm warte ich, bis das abgeleitete Objekt vollständig aufgebaut ist, bevor ich t anrufe Die virtuelle Mitgliedsfunktion. Der Thread wird jedoch gestartet, bevor das Objekt vollständig erstellt wurde.
Wie kann der virtuelle Anruf sichergestellt werden?
Welche Plattform benutzen Sie? VS2015U3 - "Ich bin C" zweimal wie erwartet. –
In dem Link in der Frage verwendet es clang, aber ich [das gleiche mit gcc] (http://coliru.stacked-crooked.com/a/688e7d3c5107e57a). Auch mit 'Microsoft Visual Studio Community 2015 Version 14.0.25431.01 Update 3' bekomme ich das gleiche. Wenn ich jedoch in VS2015 im Debug-Modus durchtrete, bekomme ich zweimal "Ich bin C". – wally
hmm das ist seltsam. Ich habe 'Microsoft Visual Studio Professional 2015 Version 14.0.25431.01 Update 3'.Funktioniert gut für beide - Debug und Release. –