Why is it illegal to take the address of an rvalue temporary?

前端 未结 6 1855
甜味超标
甜味超标 2020-11-27 05:34

According to \" How to get around the warning "rvalue used as lvalue"? \", Visual Studio will merely warn on code such as this:

int bar() {
   retu         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 05:51

    As others mentioned, we all agreed temporaries do have storage.

    why is it illegal to take the address of a temporary?

    Because temporaries are allocated on stack, the compiler is free to use that address to any other purposes it wants to.

    int foo()
    {
    int myvar=5;
    return &myvar;
    }
    
    int main()
    {
    int *p=foo();
    print("%d", *p);
    return 0;
    }
    

    Let's say the address of 'myvar' is 0x1000. This program will most likely print 99 even though it's illegal to access 0x1000 in main(). Though, not necessarily all the time.

    With a slight change to the above main():

    int foo()
    {
    int myvar=5;
    return &myvar; // address of myvar is 0x1000
    }
    
    int main()
    {
    int *p=foo(); //illegal to access 0x1000 here
    print("%d", *p);
    fun(p); // passing *that address* to fun()
    return 0;
    }
    
    void fun(int *q) 
    {
     int a,b; //some variables
     print("%d", *q);
    }
    

    The second printf is very unlikely to print '5' as the compiler might have even allocated the same portion of stack (which contains 0x1000) for fun() as well. No matter whether it prints '5' for both printfs OR in either of them, it is purely an unintentional side effect on how stack memory is being used/allocated. That's why it's illegal to access an address which is not alive in the scope.

提交回复
热议问题