user2780757
user2780757

Reputation: 191

C++ Reference Reassignment

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;
}
  1. The app sometimes crashes when the second d = *dbconn is executed.
  2. Does 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

Answers (1)

Bathsheba
Bathsheba

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

Related Questions