通过引用传递给功能的临时对象的寿命

时间:2019-02-18 11:42:58

标签: c++ object-lifetime temporary-objects

是的,之前曾问过类似的问题,但它们并不完全相同(或者至少提供的答案对我来说还不够)。

我的一般问题是:调用函数时创建的临时对象的寿命是多少?

代码:

#include <iostream>
#include <string>

using namespace std;

class A
{
public:
    A()
    {
        cout << "A()" << endl;
    }
    A(const A&)
    {
        cout << "A(const A&)" << endl;
    }
    A(A&&)
    {
        cout << "A(A&&)" << endl;
    }
    ~A()
    {
        cout << "~A()" << endl;
    }
};

class Container
{
public:
    A& getA()
    {
        return a;
    }

private:
    A a;
};

void f(A & a)
{
    cout << "f()" << endl;
}

int main()
{
    f (Container().getA());
    cout << "main()" << endl;
}

这将产生输出:

A()
f()
~A()
main()

我创建了Container的临时实例,并将对该字段的引用传递给函数f()。输出表明Container的实例在调用f()时开始生效,一直存活到函数返回并销毁为止。但也许此输出是a幸。

标准怎么说?在Container::a的正文中对f()的引用是否有效?

0 个答案:

没有答案
相关问题