指针通过引用和本地函数变量生命周期传递

时间:2016-12-09 14:23:12

标签: c++

这是代码:

#include <iostream>

void swapInt(int*& a, int*& b)
{
    int temp = *a;
    *a = *b;
    // *b = temp;   // the intended way

    std::cout << "&temp: " << &temp << '\n';
    std::cout << "b before change: " << b << '\n';

    b = &temp;                                      // this also works? UB or not?

    std::cout << "b after change: "<< b << '\n';
}

int main()
{
    int a = 4;
    int b = 10;

    int* p = &a;
    int* q = &b;

    std::cout << "q before call: " << q << '\n';

    swapInt(p, q);

    std::cout << *p << ' ' << *q << '\n';       // q is pointing to temp here

    std::cout << "q after call: " << q << '\n'; // q is pointing to temp here


    std::cout <<"\n\n";

    return 0;
}

示例输出:

q before call: 00D1F87C
&temp: 00D1F860
b before change: 00D1F87C
b after change: 00D1F860
10 4
q after call: 00D1F860

我不清楚究竟发生了什么:

1)这个UB是否正常工作,因为内存未被更改
OR
2)是否有一些规则阻止局部变量被分配给通过引用传递的指针(比如当按值返回时自动临时的生命周期被绑定到引用时)?

0 个答案:

没有答案