1

This is the code:

#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;
}

Sample output:

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

What is unclear to me is what exactly is happening:

1) Is this UB and just appears to work because the memory is not altered
OR
2) Is there some rule that prevents the local variable to be destroyed if assigned to a pointer passed by reference (like when an automatic temporary's lifetime is bound to a reference when returned by value)?

sharyex
  • 460
  • 1
  • 5
  • 17
  • 11
    It's option #1. – melpomene Dec 09 '16 at 14:24
  • there's no reference counter in C++. So it's UB. – Jean-François Fabre Dec 09 '16 at 14:25
  • Essentially [this](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) this is your issue but instead of returning by return value you are returning by parameter. – NathanOliver Dec 09 '16 at 14:25
  • @NathanOliver Yes I've read that and similar questions, just wasn't sure if it's the same issue or one of those fringe "awesome" exceptions from the rules. Hence better to ask. – sharyex Dec 09 '16 at 14:29
  • 1
    There are no exceptions to the rule that you cannot access a variable after its lifetime ends. – NathanOliver Dec 09 '16 at 14:35
  • @NathanOliver Was thinking more about maybe the lifetime of the variable is extended for whatever reasons behind the curtains. – sharyex Dec 09 '16 at 14:39

0 Answers0