When passing a class by-value, does the caller or callee call the destructor?

后端 未结 4 1157
暗喜
暗喜 2021-02-19 21:34

Suppose that I have the following (trimmed down) code:

class P { P(); P(const P&); ~P(); }

void foo(P x) {
  ...
}

         


        
4条回答
  •  轮回少年
    2021-02-19 21:40

    The idea of caller and callee looks wrong for me. You should think of scopes here.

    In the moment the stack for the function is created where the object P x in foo comes to live, the object will be "created". As this, the object will be deleted at last by leaving the scope, in your case by leaving the function.

    So there is no theoretical difference by having a local scope inside a function which introduces new objects and later on leaving this scope in the same function.

    The compiler is able to "see" how your object is used, especially modified and can by inlining the function also skip the creation of a "temporary" object as long as the code behaves "as if" written.

提交回复
热议问题