Object return in C++ [duplicate]

2019-08-03 21:54发布

This question already has an answer here:

When returning object, I thought returning pointer or reference is the right way because temporary object is created when returning an object.

In this example, hello() function returns an object of type A, and the returned value is stored in object a.

A hello()
{
    A a(20); // <-- A object is created in stack
    cout << &a << endl;
    return a; // <-- Temporary object is created for return value
}

void test1()
{
    A a = hello(); // copy constructor is called
    cout << &a << endl;
}

My expectation was there should three constructor called. However, when I executed test1() with g++ 4.8, the constructor is called only once, not trice.

class A
{
    int x;
public: 
    A() {
        cout << "Default constructor called" << endl;
    }  
    A(const A& rhs) 
    {
        this->x = rhs.x;
        cout << "Copy constructor called" << endl;
    }
    A& operator=(const A& rhs)
    {
        this->x = rhs.x;
        cout << "Copy constructor called" << endl;
    }
    A(int x) : x(x) {
        cout << "*I'm in" << endl;
    }
    ~A() {
        cout << "*I'm out" << endl;
    }
    int get() const {return x;}
    void set(int x) {this->x = x;}
};

Execution result:

*I'm in
0x7fff62bb30c0 <-- from hello()
0x7fff62bb30c0 <-- from test1()
*I'm out
  • Is this expected behavior in C++ or did I get this result because of g++ optimization?
  • The A a(20) object is generated in the stack of the hello() function, and it is supposed to be deleted on return. How the object stack can be not deleted and passed to the caller?

0条回答
登录 后发表回答