tags:

views:

144

answers:

1

When I compile the following code with g++, the object of class A seems not to be destructed when the object of class C is constructed, and the B.ref_a reference is not broken when accessed by the constructor of object of class C:

#include <iostream>

struct A
{
    A(int aa)
    {
     a = aa;
    }

    ~A()
    {
     std::cout << "A out" << std::endl;
    }

    int a;
};

struct B
{
    B(const A& a)
    : ref_a(a)
    {
    }

    ~B()
    {
     std::cout << "B out" << std::endl;
    }

    const A& ref_a;
};

struct C
{
    C(const B& b)
    {
     c = b.ref_a.a + 1;
    }

    int c;
};

int main(void)
{
    C c(B(A(1)));
    std::cout << c.c << std::endl;
}

However, is it guaranteed by the C++ language?

+6  A: 

Here, the temporary objects go out of scope when the instruction has finished its execution. That is, just after the constructor of C has returned.

And yes, this is guaranteed by the C++ language.

Samuel_xL
Thank you, kind Sir.
quant_dev
Hmm, I don't know which answer should I accept :)
quant_dev
@quanta_dev Never mind, TheSamFrom1984's answer is a good one too :)
AraK