温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++临时对象的生命周期举例分析

发布时间:2021-11-24 10:29:53 来源:亿速云 阅读:152 作者:iii 栏目:互联网科技

这篇文章主要介绍“C++临时对象的生命周期举例分析”,在日常操作中,相信很多人在C++临时对象的生命周期举例分析问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++临时对象的生命周期举例分析”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

1)一般情况:临时性对象的被摧毁,应该是对完整表达式(full-expression)求值过程中的最后一个步骤。该完整表达式造成临时对象的产生。

例:

#include <iostream>
using namespace std;

class A
{
public:
    A(int i): m_i(i)
    {
        cout << "A(): " << m_i << endl;
    }

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

    A operator+(const A& rhs)
    {
        cout << "A operator+(const A& rhs)" << endl;
        return A(m_i + rhs.m_i);
    }

    int m_i;
};

int main()
{
    A a1(1), a2(2);
    a1 + a2;
    cout << "------------------------------------" << endl; //运行到这里,a1 + a2产生的临时变量已经被释放
    return 0;
}

运行结果:
A(): 1
A(): 2
A operator+(const A& rhs)
A(): 3
~A(): 3
------------------------------------
~A(): 2
~A(): 1

两个例外:
2)凡含有表达式执行结果的临时性对象,应该存留到object的初始化操作完成为止。

例:

#include <iostream>
using namespace std;

class A
{
public:
    A(int i = 0): m_i(i)
    {
        cout << "A(): " << m_i << endl;
    }

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

    A operator+(const A& rhs)
    {
        cout << "A operator+(const A& rhs)" << endl;
        return A(m_i + rhs.m_i);
    }

    A& operator=(const A& rhs)
    {
        cout << "A& operator=(const A& rhs)" << endl;
        m_i += rhs.m_i;
        return *this;
    }

    int m_i;
};

int main()
{
    A a1(1), a2(2);
    A a3;
    a3 = a1 + a2; //a1 + a2产生的临时变量在a3的赋值操作完成后,才释放
    return 0;
}

运行结果:
A(): 1
A(): 2
A(): 0
A operator+(const A& rhs)
A(): 3
A& operator=(const A& rhs)
~A(): 3
~A(): 3
~A(): 2
~A(): 1

3)如果一个临时性对象被绑定于一个reference,对象将残留,直到被初始化之reference的生命结束,或直到临时对象的生命范畴(scope)结束——视哪一种情况先到达而定。

例:

#include <iostream>
using namespace std;

class A
{
friend ostream& operator<<(ostream& os, const A&);
public:
    A()
    {

    }

    A(const A&)
    {
        cout << "A(const A&)" << endl;
    }

    ~A()
    {
        cout << "~A()" << endl;
    }
};

ostream& operator<<(ostream& os, const A&)
{
    os << "ostream& operator<<(ostream& os, const A&)" << endl;
    return os;
}

const A& f(const A& a)
{
    return a;
}

int main(int argc, char* argv[])
{
    {
        const A& a = A();
        cout << "-------------------" << endl;
    }//直到被初始化之reference的生命结束
       
    cout  << f(A()) << endl; //直到临时对象的生命范畴(scope)结束:
                             //临时对象的const引用在f的参数上(而不是返回值)。
                             //这个引用在f()返回的时候就结束了,但是临时对象未必销毁。
    cout << "-------------------" << endl;
   
    return 0;
}

运行结果:
-------------------
~A()
ostream& operator<<(ostream& os, const A&)

~A()

到此,关于“C++临时对象的生命周期举例分析”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI