C++: Life span of temporary arguments?

后端 未结 4 656
南旧
南旧 2020-11-22 09:58

When creating a new instance of a MyClass as an argument to a function like so:

class MyClass
{
  MyClass(int a);
};    

myFunction(MyClass(42))         


        
4条回答
  •  忘了有多久
    2020-11-22 10:32

    Everyone has rightly cited 12.2/3 or similar, which answers your question:

    Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created.

    I find it amusing that over the next page in my printing of the standard, 12.2/4 says:

    There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression.

    Neither of them applies to your example, they both relate to the use of temporaries in initializers. But it does go to show that you have to keep your wits about you when dealing with a tricky beast like the C++ standard.

提交回复
热议问题