returning a heap block by reference in c++

Posted by basicR on Programmers See other posts from Programmers or by basicR
Published on 2013-11-04T07:28:16Z Indexed on 2013/11/04 10:16 UTC
Read the original article Hit count: 254

Filed under:
|

I was trying to brush up my c++ skills. I got 2 functions:

concat_HeapVal() returns the output heap variable by value
concat_HeapRef() returns the output heap variable by reference

When main() runs it will be on stack,s1 and s2 will be on stack, I pass the value by ref only and in each of the below functions, I create a variable on heap and concat them.

When concat_HeapVal() is called it returns me the correct output.
When concat_HeapRef() is called it returns me some memory address (wrong output). Why?

I use new operator in both the functions. Hence it allocates on heap.
So when I return by reference, heap will still be VALID even when my main() stack memory goes out of scope.

So it's left to OS to cleanup the memory. Right?

string& concat_HeapRef(const string& s1, const string& s2)
{

    string *temp = new string();
    temp->append(s1);

    temp->append(s2);
    return *temp;
}


string* concat_HeapVal(const string& s1, const string& s2)
{

    string *temp = new string();
    temp->append(s1);

    temp->append(s2);
    return temp;

}

int main()

{

    string s1,s2;
    string heapOPRef;
    string *heapOPVal;
    cout<<"String Conact Experimentations\n";
    cout<<"Enter s-1 : ";
    cin>>s1;
    cout<<"Enter s-2 : ";

    cin>>s2;

    heapOPRef = concat_HeapRef(s1,s2);
    heapOPVal = concat_HeapVal(s1,s2);

    cout<<heapOPRef<<"  "<<heapOPVal<<" "<<endl;
        return -9;
}

© Programmers or respective owner

Related posts about c++

Related posts about return-type