Where are temporary object stored?

后端 未结 4 1162
一个人的身影
一个人的身影 2020-12-01 12:52

IMO temporary objects are stored in dynamic (heap) memory, but I\'m not sure. Can you please confirm or deny my thoughts?

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 13:30

    This is highly implementation dependent, but they probably reside in automatic storage.

    Note that the scope can be counter-intuitive, because of optimizations.

    The following:

    class A
    {
    //...
    };
    
    //....
    
    A foo()
    {
       A a;
       return a;
    }
    

    Here, the object a doesn't necessarily reside only inside the function's scope, but RVO can occur.

    Also, when passing by value a temporary object, it might not get destructed immediately.

    void foo(A a);
    //...
    
    foo( A() );
    

    Here, a temporary is not necessarily only alive in that line, but can be constructed directly inside the method's argument stack.

提交回复
热议问题