如何在没有创建副本的情况下返回对象? [英] how to return object without create copy of that?

查看:72
本文介绍了如何在没有创建副本的情况下返回对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了简单的 C++ 类来测试 C++ 对象何时销毁;现在我有一个问题,当一个对象通过函数返回时,c++ 创建一个新对象并返回它,当返回引用销毁对象时,我的错误是什么?

I develop simple c++ class to testing when c++ objects destroy; now I have a problem, when an object return by function, c++ create a new object and return that and when return reference destroy object what is my mistake ?

下面附上简单的类.

#include <iostream>

using namespace std;

static int freeCounter=0;

class TestCopy {
private:
    string pStr;
public:
    TestCopy(const TestCopy &obj){
        pStr=obj.pStr;
    }
    TestCopy(string &test){
        pStr=test;
    }
    ~TestCopy(){ freeCounter++; cout << freeCounter <<"\t" << pStr << endl; }

    TestCopy get(){
        TestCopy x=*this; 
        return TestCopy(x); // -> TestCopy(x) is first destroy in result
    }

    string getStr(){
        return pStr;
    }
};

int main(){
    string xstr="test";
    TestCopy x(xstr); // x is third destroy
    TestCopy x2=x.get(); // x2 is second destroy

    cout << x.getStr() << endl;

    return 0;
}

和结果

1   test
test
2   test
3   test

推荐答案

感谢@seaman 的帮助我发现了我的错误.通过改变

thank you @seaman with your help I found my mistake. by changing

TestCopy x=*this;

const TestCopy &x=*this;

问题已解决

这篇关于如何在没有创建副本的情况下返回对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆