【问题标题】:Reference to value in scope produces garbage在范围内引用值会产生垃圾
【发布时间】:2018-03-28 19:13:44
【问题描述】:

我想编写一个将引用作为字段的类,但我发现即使是这个初始化引用并打印其值的简单代码也失败了:

struct Referencer {
    explicit Referencer(int in) : num(in) {}
    void print() {
        std::cout << num << std::endl;
    }
    int &num;
};
int main() {
    int longlived = 500;
    Referencer ref(longlived);
    ref.print();
}

结果是垃圾(没有抛出错误,也没有程序段错误)。我的理解是变量longlivedReferencer 的实例具有相同的生命周期,因为它们都在堆栈中声明并且具有相同的范围。因此,当调用ref.print() 时,字段num 应该指向有效的堆栈内存。为什么不是这样?

【问题讨论】:

  • 仔细看Referencer(int in) : num(in)
  • in 离开构造函数后不再在作用域内。也许你的意思是int &amp; in
  • "我的理解是变量longlivedReferencer的实例具有相同的生命周期"当然可以。但是..您的Referencer::num 没有引用longlived
  • 哎呀,我的错。
  • 为了更好地理解,试着用指针做同样的事情......

标签: c++ class memory reference field


【解决方案1】:

Referencer 的构造函数按值获取参数。所以in 拥有longlived 中值的副本。然后将num 初始化为对in 的引用,一旦构造函数返回,它就会被销毁。

如果您希望num 持有对用作构造函数参数的对象的引用,请通过引用传递in,如explicit Referencer(int &amp;in) : num(in) {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 2016-12-31
    • 2015-05-24
    • 1970-01-01
    相关资源
    最近更新 更多