Search code examples
c++objectreferencedestroy

how to return object without create copy of that?


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 ?

simple class attached below.

#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;
}

and result

1   test
test
2   test
3   test

Solution

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

    TestCopy x=*this;
    

    with

    const TestCopy &x=*this;
    

    problem solved