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

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

    The standard answers this question in [expr.call]/4, with a surprising amount of elaboration:

    ... The initialization and destruction of each parameter occurs within the context of the calling function. [ Example: The access of the constructor, conversion functions or destructor is checked at the point of call in the calling function. If a constructor or destructor for a function parameter throws an exception, the search for a handler starts in the scope of the calling function; in particular, if the function called has a function-try-block (Clause 18) with a handler that could handle the exception, this handler is not considered. —end example ]

    In other words, the destructor is invoked by the calling function.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-19 22:03

    The destructor is called whenever an object's lifetime ends, which includes

    end of scope, for objects with automatic storage duration and for temporaries whose life was extended by binding to a reference

    So bar which is the owner of copied object will call dtor on the copied object. Cppreference

    0 讨论(0)
提交回复
热议问题