C++中return返回时有没有创建临时对象调用构造函数问题

1.如果返回值被用在赋给其它对象或作为其它函数的参数时,函数内部在已经创建有对象情况下,返回时时不在创建零时对象的,如果函数内的对象没有创建,只在返回时出现过,那么会在返回时创建,这个就是因为必须得有实例对象才能传值。

#include<iostream>
#include<string>
using namespace std;

string GetMyString()
{
    return "This is a string";
}


class zheng
{
   private:
       int a;
    public:
        zheng() { a = 0;
        cout << "Mvalue copy construct" << endl; };
        zheng(zheng& z){
            cout << "Lvalue copy construct" << endl;
        }
        zheng(zheng && z){
            cout << "Rvalue copy construct" << endl;
        }
        zheng(const int&& x):a(x){
            cout << "value copy construct" << endl;
        }
        ~zheng(){
            cout << "destruct construct" << endl;
        }
        void set(int b)
        {
            a = b;
        }
};


struct test
{
    private:
        zheng a;

    public:
        test( zheng& s)
        {
            cout << "L zheng construct" << endl;
        }
        test( zheng&& s)
        {
            cout << "R zheng construct" << endl;
        }
        ~test(){
            cout << " zheng destruct" << endl;
        }
};


zheng GetMyvalue()
{
     zheng x1;  //这里创建了返回是就不会创建了,如果直接在返回的地方写zheng,则会在返回的地方创建一个零时对象
    // cout << " construct" << endl;
     //x1.set(7);
     //zheng x2(x1);
     return x1;
}





int main(int argc, char const *argv[])
{
    // {
    //     const string &s = GetMyString();
    // }

    // string a = "1234";
    {
         // GetMyvalue();
          //zheng s(GetMyvalue());
          //zheng y = s;
         test s{GetMyvalue()};
        //  zheng s;
        //  zheng *p = &s;

        //  zheng &x1 = s;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值