为什么参考有时会处理对象的生命周期

时间:2016-07-10 11:50:26

标签: c++ reference lifetime

我发现了奇怪的行为,并希望了解它的工作方式和原因(在msvc 14.0,Visual Studio 2015上测试)。

让我们假设我们有结构test_struct

   struct test_struct
   {
      test_struct() : _number(5) {}
      int _number;
      ~test_struct()
      {
         static int i = 0;
         std::cout << i++ << std::endl;
      }

      test_struct& get_me() { test_struct a; return a; }
   };

我们有以下代码:

   {
      test_struct();                         //(0) will be written 0, because object was created and died just at same moment, because it's scope is a point of it's creation.
      test_struct struct2;                   //(1) nothing will be written, because object is still in scope
      test_struct& ref1 = struct2.get_me();  //(2) trying to get reference to object that is out of scope, keeping reference to object do not save it. Will be written 1.
      test_struct& ref2 = test_struct();     //(3) Nothing will be written !!?? Despite fact, that object was created similar as at (0), so had to die immediately, and despite fact, that keeping reference to such object do not save it, as we learned from (2)
      {
         test_struct& ref3 = struct2;        //nothing will be written, because moving out of reference scope do not destruct object
      }
   }                                         //will be written 2 and 3, because now moving out of reference scope destructs object

问题是:

  1. 如果现有引用可以处理对象存在,为什么第(2)行会引导 未定义的行为和丢失的对象?
  2. 如果现有的引用不能处理对象,为什么没有 第(3)行的破坏,它在参考时发生 离开范围?
  3. 如果在任何范围内构建的没有名称的对象直到退出 从范围,为什么在第(0)行有这种物体的破坏?
  4. 如果在任何范围内构建没有名称的对象,则直到 退出范围,并且引用不处理对象,为什么对象 在第(3)行没有名字的地方建造后没有被破坏 创建
  5. 看起来有时引用可以处理对象,有时候不会。是否有任何澄清?

0 个答案:

没有答案