简体   繁体   English

将const引用返回给临时对象的成员

[英]returning const reference to a member of a temporary object

What happens when a const reference to aa member of a temporary object is returned; 当返回对临时对象的成员的const引用时会发生什么; What is the lifetime of that object; 那个对象的生命周期是多少;

Eg 例如

struct temp
{
  T m_mine;

  static temp make()
  {
    return temp();
  }
};

T const & foo()
{
  return temp::make().m_mine;
}

What is the behavior with c++98 and c++11? c ++ 98和c ++ 11的行为是什么?

The constness of the object or the referee type doesn't matter in this context: it's simply a return of a reference to an object that at that time has ceased to exist. 在这种情况下,对象或裁判类型的常量无关紧要:它只是返回对当时不再存在的对象的引用。 Using the reference is then Undefined Behavior. 然后使用引用是未定义的行为。

Likewise, if you bind a member reference to const, to an object, that does not prolong the life of the referee. 同样,如果将对const的成员引用绑定到对象,则不会延长裁判的生命。

Object lifetime extension is only for the case of binding a local reference to an object, and only for the cases of reference to const object or rvalue reference. 对象生存期扩展仅适用于将本地引用绑定到对象的情况,仅适用于引用const对象或rvalue引用的情况。


The example code as it was at the time I wrote this, has several problems. 我写这篇文章时的示例代码有几个问题。 Please only post real code (to the degree possible). 请仅发布实际代码 (尽可能发布)。 And it should be pasted, not retyped. 它应该粘贴,而不是重新输入。

(Also, since there is now at least 2 answers referring to the problems of the code, it's too late to correct it without possibly changing the context of the answers and thereby invalidating them. So it's important to get the code correct in the original posting. Worth keeping in mind for next SO question.) (另外,由于现在至少有2个答案涉及代码的问题,因此在不改变答案的上下文并因此使其无效的情况下纠正它为时已晚。因此,在原始发布中获取代码非常重要值得记住下一个SO问题。)

Your code is incorrect in multiple accounts before it is even getting to compile: 在进行编译之前,您的代码在多个帐户中是不正确的:

  • there is at least a semicolon missing after the type declaration 类型声明后至少缺少一个分号
  • the code uses the non- static member make() as if it is a static function 代码使用非static成员make() ,就像它是static函数一样

Once getting over that: the reference returned refers to a subobject of an object which is destroyed after the return statement is executed and before anything can get hold of it. 一旦克服了这一点:返回的引用引用了一个对象的子对象,该对象在执行return语句之后以及任何可以获取它之前被销毁。 That is, there is a stale reference return. 也就是说,有一个陈旧的参考回报。 Any access to this reference will result in undefined behavior. 对此引用的任何访问都将导致未定义的行为。 If you are lucky, the program crashes at this point. 如果运气好的话,程序会在此时崩溃。 If you are unlucky it does something you like it to happen. 如果你运气不好,它会做你喜欢的事情。 For example it may "work" until the program is demonstrated to a client or an investor at which point it may decide to rather display insults. 例如,它可以“工作”,直到程序被证明给客户或投资者,此时它可能决定反而显示侮辱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM