Address of a reference

前端 未结 5 1211
北恋
北恋 2021-01-16 02:40

So I am having a discussion with a friend about reference and pointers.

What we got talking about is \"you can take an address of a pointer but you cant take an addr

5条回答
  •  我在风中等你
    2021-01-16 03:05

    Just for completenesses sake: There is a way to produce a pointer to a reference.

    auto foo(int &x){
        return [&]{std::cout << x;};
    }
    

    What the compiler is allowed to do here is not to capture a reference tox but to capture the stack pointer instead. Based on the stack pointer the compiler knows the offsets to the various parameters of foo and may save some memory for the lambda. However, after the lambda has been returned the parameters of foo are gone and the lambda references objects that do not exist. Therefore it is forbidden / UB to do this.

提交回复
热议问题