【问题标题】:Copy constructor initialize a reference member in initialization list causes dangling pointer复制构造函数在初始化列表中初始化引用成员导致悬空指针
【发布时间】:2020-01-09 01:00:03
【问题描述】:

我有一个带有引用成员 num 的 A 类。我编写了一个复制构造函数,在初始化列表中初始化num。但是结果似乎很奇怪,打印出来的值不应该是100吗?我的程序什么时候修改了a.numaa.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;
}

输出是:

-1077613148
-1077613148
0xbfc4ed94 0xbfc4ed94

【问题讨论】:

标签: c++ reference copy-constructor


【解决方案1】:

这个问题与复制构造函数无关。在构造函数A::A(int n) 中,您将成员引用num 绑定到构造函数参数n,在离开构造函数时将被销毁,使引用num 悬空。对它的任何取消引用都会导致 UB。

您可以将构造函数更改为获取引用,

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

然后像这样使用它

int i = 100;
A a(i);

LIVE

【讨论】:

  • 哇,你真是天才!这解决了我的问题!非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
  • 2011-05-02
  • 1970-01-01
  • 2015-10-09
  • 2020-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多