简体   繁体   中英

Copy constructor initialize a reference member in initialization list causes dangling pointer

I have a class A with a reference member num . And I have written a copy constructor that initialize num in the initialization list. But the outcome seems strange, shouldn't the printed out value be 100? And when did my program modified the value of a.num and aa.num ?

#include <iostream>
using namespace std;

class A{
public:
    int& num;
    A(int n):num(n){}
    A(const A& obj):num(obj.num){}

    void print(){
        cout << num << endl;
    }
};

int main(){

    A a(100);
    A aa = a;
    a.print();  //Expected to be 100, but it isn't
    aa.print(); //Also expected to be 100, but it isn't

    //The address of a.num and aa.num are the same, so both of them are referencing to the same place. But the question is why the value isn't 100 but a strange value
    cout << &(a.num) << " " << &(aa.num) <<endl;
}

The output is:

-1077613148
-1077613148
0xbfc4ed94 0xbfc4ed94

The issue has nothing to do with copy constructor. In the constructor A::A(int n) , you're binding the member reference num to the constructor parameter n , which will be destroyed when get out of the constructor, left the reference num dangled. Any dereference on it leads to UB.

You might change the constructor to taking a reference,

A(int& n):num(n){}

then use it like

int i = 100;
A a(i);

LIVE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM