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

后端 未结 4 766
暗喜
暗喜 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:51

    The caller destroys it. See https://en.cppreference.com/w/cpp/language/lifetime. Quoting:

    All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation.

    Also keep this as general rule - one, who creates, destroys. Usually in reversed order.

提交回复
热议问题