The temporary D
is being destructed, and you have undefined behavior by calling a method of an object whose lifetime has ended.
When you have undefined behavior, working just fine is one possible behavior.
题
I'm trying to learn how to use rvalue references. Can anyone explain why the following code works? Why isn't the D
that is sent from B
's initialization list to A
's constructor not destructed when the B
's constructor goes out of scope?
class C {
public:
void test() {
std::cout << i << " ok!\n";
}
private:
int i = rand();
};
class D: public C {};
class A {
public:
A(C &&c) : m_c(c) {}
void test() {m_c.test();}
private:
C &m_c;
};
class B: public A {
public:
B() : A(D()) {}
};
int main(int argc, char** argv) {
A *a = new B();
a->test();
}
解决方案
The temporary D
is being destructed, and you have undefined behavior by calling a method of an object whose lifetime has ended.
When you have undefined behavior, working just fine is one possible behavior.