Question

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();
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top