Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does binding a reference actually evaluate the operand?

Consider this code:

int& x=*new int;

Does RHS of the assignment actually dereference the newly-created pointer, leading to UB due to reading uninitialized variable? Or can this be legitimately used to later assign a value like x=5;?

like image 444
Ruslan Avatar asked Jun 22 '16 21:06

Ruslan


1 Answers

As far as I can tell, none of what you've done involves undefined behavior.

It does, however, immediately create a risk of a memory leak. It can be quickly resolved (since &x would resolve to the address of the leaked memory, and can therefore be deleted) but if you were to leave scope, you would have no way of retrieving that pointer.

Edit: to the point, if you were to write

int& x=*new int;
x = 5;

std::cout << x << std::endl;

std::cin >> x;

std::cout << x << std::endl;

The code would behave as though you had simply declared x as int x;, except that the pointer would also be left dangling after the program exited scope.

You would achieve undefined behavior if you were to attempt to read the uninitialized variable before assigning it a value, but that wouldn't be untrue if x were stack allocated.

like image 191
Xirema Avatar answered Nov 10 '22 22:11

Xirema