开发者

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

开发者 https://www.devze.com 2023-03-20 13:25 出处:网络
Generally this discussion is up to the local function variable only: void foo (const int &i) { // use i till foo() ends

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 a开发者_运维知识库llocated A ?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号