Search code examples
c++temporary-objects

How to comprehend "Temporary objs are destroyed as the last step in evaluating the full-expression"?Could anyone make it clear by some simple example?


As per the documentation(), which says:

When an implementation introduces a temporary object of a class that has a non-trivial constructor ([class.default.ctor], [class.copy.ctor]), it shall ensure that a constructor is called for the temporary object. Similarly, the destructor shall be called for a temporary with a non-trivial destructor ([class.dtor]). Temporary objects are destroyed as the last step in evaluating the full-expression ([intro.execution]) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. The value computations and side effects of destroying a temporary object are associated only with the full-expression, not with any specific subexpression.

How to comprehend "Temporary objects are destroyed as the last step in evaluating the full-expression ([intro.execution]) that (lexically) contains the point where they were created."?Could anyboday make it clear by some simple examples?


Solution

  • Simple example. This expression produces a temporary object:

    std::string("test")
    

    Here, that expression is used as a subexpression:

    function(std::string("test"));
    // point A
    

    At point A, the temporary object has been destroyed because the point is after the full-expression where the temporary object was created.


    Here is an example of how to write a bug if this rule is not understood:

    const std::string& function(const std::string& arg) {
        return arg;
    }
    
    const std::string& ref = function("test");
    std::cout << ref;
    

    Here, the temporary object that was created as the argument is destroyed after the full expression, and therefore ref has become invalid - a dangling reference. The behaviour is undefined when the invalid reference is inserted into the output stream.