C++ destruction of temporary object in an expression

前端 未结 4 1456
孤街浪徒
孤街浪徒 2020-12-06 03:44

Given the following code:

#include 

struct implicit_t
{
    implicit_t(int x) :
        x_m(x)
    {
        std::cout << \"ctor\" <         


        
4条回答
  •  春和景丽
    2020-12-06 04:20

    Since there is a constructor which can accept the argument passed into the F() function the complier creates the object on the fly before putting the arguments on the stack. As can be see in the disassembly below. literal numbers are treated by default as ints so there is an acceptable conversion.

    001115C5  call        implicit_t::implicit_t (11112Ch) 
    001115CA  mov         dword ptr [ebp-4],0 
    001115D1  mov         esi,esp 
    001115D3  mov         eax,dword ptr [__imp_std::endl (11A308h)] 
    001115D8  push        eax  
    001115D9  lea         ecx,[ebp-0D4h] 
    001115DF  push        ecx  
    001115E0  call        f (111113h) 
    

    Your temp object hangs around until the expression is fully evaluated. this can be made more evident if you add another call to your function.

    int main()
    {
        std::cout << f(42) << std::endl;
    
        std::cout <

    Which has an output of

    ctor
    42
    dtor
    ctor
    80
    dtor
    

提交回复
热议问题