C++ Copy Generator

Asked 2 years ago, Updated 2 years ago, 22 views

#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 << "Destory 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);
    cout << "Return Obj " << &tempRef << endl;

    return 0;
}

I know why the copy generator cannot be called for tempRef, but other than that Is it because the reason why the destructor cannot be called for tempRef is the same reason why the copy generator cannot be called, and so when the destructor is called for a temporary object, tempRef is also the same as the destructor is called?

c++

2022-09-21 18:10

2 Answers

New Object : 0x7ffeab864678
New Copy obj: 0x7ffeab864668
Parm ADR: 0x7ffeab864668
New Copy obj: 0x7ffeab864670
Destory obj: 0x7ffeab864670
Destory obj: 0x7ffeab864668

New Copy obj: 0x7ffeab864650
Parm ADR: 0x7ffeab864650
New Copy obj: 0x7ffeab864658
Destory obj: 0x7ffeab864650
Return Obj 0x7ffeab864658
Destory obj: 0x7ffeab864658
Destory obj: 0x7ffeab864678

Destory obj: 0x7ffeab864658 is the destructor call result for tempRef in the following execution result.

By omitting copy SimpleFuncObj(obj) will be tempRef.

Because SimpleFuncObj() returns a value copy, the copy constructor is called at return, but the copy process can be omitted if it is called tempRef without having to copy the temporary object created again.

C++ compilers are aware of this and omit copies to eliminate processes that are not in use as much as possible.

More precisely, you can understand that the tempRef variable generated it immediately without creating the temporary object itself.

Let me explain in more detail.

SoSimple tempRef = SimpleFuncObj(obj);In , the function's return object is usually called a temporary object (more precisely, rvalue) because it has no name. This temporary object is passed to tempRef as a factor for the substitution or copy constructor, which causes the substitution or copy constructor to be omitted in C++, so the temporary object is named tempRef without being called. Because the object is named, the object exists within the life cycle in which the name is valid. Unnamed objects are removed at the end of the expression, but in this situation, they are named tempRef, so they will survive until the main ends of the main.

In other words, tempRef is a temporary object returned as a result of a function call.


2022-09-21 18:10


2022-09-21 18:10

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.