【问题标题】:Is reference binding to a temporary of a temporary undefined behavior?引用是否绑定到临时未定义行为的临时?
【发布时间】:2018-08-22 05:57:03
【问题描述】:

在下面的sn-p中,球体的生命周期是否以r的值不是未定义的方式延长?

 struct Sphere {
   auto& radius() const { return _radius;}
   float _radius{};
 };
 struct Capsule {
   auto sphere() const { return Sphere{12.0}; }
 };
 auto func() {
   auto capsule = Capsule{};
   const auto& r = capsule.sphere().radius();
   std::cout << r;
 }

我知道 const 引用会延长临时对象的生命周期,但我不确定如果临时对象的成员被绑定会发生什么。

注意:我很怀疑这个 sn-p 的等价物会给我带来错误,但 Clang 和 Visual Studio 都没有发出警告。

【问题讨论】:

标签: c++ reference lifetime


【解决方案1】:

临时Sphere-object 的生命周期只延长到包含调用的完整表达式完成为止。完整的表达式是const auto&amp; r = capsule.sphere().radius(); 并且不会更长,因此r 的寿命比完整的表达式更长,而且是暂时的。所以我会明确投票支持未定义的行为。

【讨论】:

    【解决方案2】:

    为了延长生命周期,引用必须绑定到纯右值(然后将其具体化为临时对象,以便引用可以绑定到某些东西)。但是,capsule.sphere().radius() 不是纯右值;它是一个指向Sphere::_radius 的左值。因此不会发生生命周期延长,Sphere 对象及其_radius 成员将在完整表达式结束时被销毁。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-23
      • 2013-07-04
      • 1970-01-01
      • 2019-07-02
      • 2012-02-25
      • 1970-01-01
      • 2020-09-16
      相关资源
      最近更新 更多