Reputation: 191
I am seeing undefined behaviour in below code. I can't quite pin-point the exact issue, it'd be much help if someone could take a look and assist. Below is built using gcc 6.3.1.
DBConn* dbconn = new DBConn();
DBConn& d = *dbconn; //reference
....
delete dbconn;
dbconn = new DBConn();
d = *dbconn;
Assignment (=) operator of DBConn
DBConn& DBConn::operator =(const DBConn &rhs) {
if(this != &rhs) {
// deletes member variable pointers initialised with objects created using new operator
// deep copies some member variables
}
return *this;
}
d = *dbconn
is executed.d = *dbconn
reassign the reference variable?From what I could gather, the app would go into undefined behaviour when memory address of d
is not same as dbconn
; executing the code in assignment operator's overloaded method because this != &rhs
.
Upvotes: 0
Views: 106
Reputation: 234705
The reference d
is dangling once dbconn
is deleted.
Yes, the behaviour on accessing d
after that is undefined. (Note that the pointer value dbconn
is indeterminate after the delete
.)
References cannot be rebound, so the subsequent
d = *dbconn;
yields a diagnostic.
Upvotes: 4