Order of constructor and destructor calling?

孤者浪人 提交于 2020-01-06 15:04:28

问题


I cannot understand the order of constructor and destructor calls? What will execute first in this statement A b=f(a)? Can someone please help me out?

#include<iostream>
using namespace std;

class A {
    int x;

    public:
        A(int val = 0)
        :x(val) {
            cout << "A " << x << endl << flush;
        }
        A(const A& a) {
            x = a.x;
            cout << "B " << x << endl << flush;
        }
        void SetX(int x) {
            this->x = x;
        }
        ~A() {
            cout << "D " << x << endl << flush;
        }
};

A f(A a) {
    cout << " C " << endl << flush;
    a.SetX(100);
    return a;
}

int main()
{
    A a(1);
    A b=f(a);
    b.SetX(-100);
    return 0;
}

Output Window:

A 1
B 1
 C
B 100
D 100
D -100
D 1

Why does it print B 1 in line 2 of the output window?


回答1:


"Why does it print B 1 in line 2?"

Because the copy constructor was called from this statement

A b=f(a);

The function f() requires A being passed by value, thus a copy for this parameter is made on the function call stack.


If your next question should be, how you can get over this behavior, and avoid to call the copy constructor, you can simply pass the A instance as a reference to f():

    A& f(A& a) {
  // ^    ^
        cout << " C " << endl << flush;
        a.SetX(100);
        return a;
    }

Side note: endl << flush; is redundant BTW, std::endl includes flushing already.



来源:https://stackoverflow.com/questions/29854010/order-of-constructor-and-destructor-calling

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