开发者

In what order do C++ objects passed as arguments to constructors of other objects go out of scope?

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;
}

Howeve开发者_高级运维r, is it guaranteed by the C++ language?


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++ standard.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜