Using Temporary Objects in c++

Asked 2 years ago, Updated 2 years ago, 30 views

The return of the SimpleFuncObj function at the point where the annotation below is displayed is an object, and in the process, a temporary variable is generated and a reference value is returned.

And if you look at the results window below, SoSimpletempRef = SimpleFuncObj(obj) is assigning the name tempRef to the temporary object returned..

However, if the object tempRef is to refer to the reference value, SoSimpletempRef = SimpleFuncObj(obj)SoSimple &tempRef = SimpleFuncObj(obj)?

Is the above just a feature of a temporary variable? If not, I wonder why it works even if it does.

The code and the result value are written below.

#include<iostream>
using namespace std;

class SoSimple
{
private:
    int num;
public:
    SoSimple(int n) : num(n)
    {
        cout << "New object: " << this << endl; 
    }
    SoSimple(const SoSimple& copy) :num(copy.num)
    {
        cout << "New Copy obj: " << this << endl;
    }
    ~SoSimple()
    {
        cout << "Destroy obj:" << this << endl;
    }
};

SoSimple SimpleFuncObj(SoSimple ob)
{
    cout << "Parm ADR: " << &ob << endl;
    return ob;
}
int main(void)
{
    SoSimple obj(7); 
    SimpleFuncObj(obj);

    cout << endl;
    SoSimple tempRef = SimpleFuncObj(obj); What I'm curious about!
    cout << "Return Obj" << &tempRef << endl;
    return 0;
}

c++

2022-09-22 16:46

1 Answers

Hi, everyone. It's been a while since I've been here and I have a good question.

I'm sure you've already solved your curiosity, but...I'm leaving an answer just in caseHaha

As you asked, the result may look the same whether or not you add a reference to the variable that receives the return value in that code.

But the principle of operation is different, so I think you should keep this in mind.

To summarize the differences between the two cases,

int main()
{
    SoSimple obj(7); 

    SoSimple returnVal = SimpleFuncObj(obj);    // Case number one
    cout << "Return Obj: " << &returnVal << endl;

    SoSimple& tempRef = SimpleFuncObj(obj);    // Case number two
    cout << "Temp Obj: " << &tempRef << endl;

    return 0;
}

In fact, the above code is not different between the two cases in terms of the results. But in more complex situations, differences occur.

(If those variables are passed to the template factor, the type inference is applied differently because number 1 is the value type and number 2 is the reference type.)


2022-09-22 16:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.