What is the lifetime of the class data member which const reference to a rvalue?

只愿长相守 提交于 2019-12-22 08:57:59

问题


Generally this discussion is up to the local function variable only:

void foo (const int &i)
{
  // use i till foo() ends
}
foo(3);

But, does this rule applies to the class member also ?

struct A {
  const int &a;
  A () : a(3) {}  // version 1
  A (const int &i) : a(i) {} // version 2
};

Now A used as,

{
  return ()? new A : new A(3) : new A(some_local_variable);
}

Will the contents of a remain same through out the life time of the all 3 newly allocated A ?


回答1:


The C++03 standard (Section "12.2/5 Temporary objects") answers your question aptly:

The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits. A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call.




回答2:


If you allocate an object using new, it will remain in memory forever - until you delete it. It's not a temporary object.

a is a member of A, and as such part of the allocation.

EDIT: Thanks for the comments. I would say - no, this is not correct. Consider this:

struct A {
  const int &a;
  A () : a(3) {}  // version 1
  A (const int &i) : a(i) {} // version 2
};

void foo() {
  A *pA;

  {
     int x;
     pA = new A(x);
  }

  // Now pA->a is pointing to the address where `x` used to be,
  // but the compiler may very well put something else in this place now
  // because x is out of scope.
}

The answer is more obvious if the lifetime of the A object spans across several functions.

Side note: I find the word "contents" a bit ambiguous here. Equate the reference with a pointer, so your a is basically pointing to an integer. const or not, if the integer does no longer exist (because it was on the stack and has been removed), your a - while still pointing to the same address in memory - is referencing something else now. The GotW article appears to be talking about the compiler prolonging the lifetime of the object being pointed to by the reference. The reference itself, again, is just a pointer.



来源:https://stackoverflow.com/questions/6715370/what-is-the-lifetime-of-the-class-data-member-which-const-reference-to-a-rvalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!