本文介绍了临时绑定到聚合的生命周期初始化的struct成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

  class foo 
{
}

class bar:public foo
{
public:
〜bar(){printf(〜bar()\\\
); }
};

class zab:public foo
{
public:
〜zab(){printf(〜zab()\\\
); }
};

struct foo_holder
{
const foo& f;
};

int main()
{
foo_holder holder [] = {{bar()},{zab()}};
printf(done!\\\
);
return 0;
}

输出为:

 〜bar()
〜zab()
done!

C ++ 0x有一个子句,指定这可以在用作新的初始化器时创建悬挂引用,但是它没有说明(至少没有找到)有临时的const引用的聚合初始化。



这是未指定的行为吗?


//groups.google.com/group/comp.std.c++/msg/9e779c0154d2f21brel =nofollow> http://groups.google.com/group/comp.std.c++/msg/9e779c0154d2f21b



基本上,标准没有明确地定位它;因此,它应该与本地声明的引用行为相同。


Given the following code:

class foo
{
};

class bar: public foo
{
public:
    ~bar() { printf("~bar()\n"); }
};

class zab: public foo
{
public:
    ~zab() { printf("~zab()\n"); }
};

struct foo_holder
{
    const foo &f;
};

int main()
{
    foo_holder holder[]= { {bar()}, {zab()} };
    printf("done!\n");
    return 0;
}

the output is:

~bar()
~zab()
done!

C++0x has a clause that dictates this can create dangling references when used as a new initializer, but it says nothing (at least nothing I can find) about aggregate initialization of const references with temporaries.

Is this unspecified behavior then?

解决方案

I got an answer on comp.std.c++:

http://groups.google.com/group/comp.std.c++/msg/9e779c0154d2f21b

Basically, the standard does not explicitly address it; therefore, it should behave the same as a reference declared locally.

这篇关于临时绑定到聚合的生命周期初始化的struct成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:23