Object return in C++ [duplicate]

落爺英雄遲暮 提交于 2019-12-11 07:38:29

问题


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?

来源:https://stackoverflow.com/questions/17159321/object-return-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!