C++ 了解变量生命周期和绑定生命周期之间的区别

C++ Understanding the difference between Variables lifetime,and binding lifetime

我无法理解变量生命周期和绑定生命周期的概念。

考虑以下任意函数

可变生命周期

Lifetime is the time duration where an object/variable has memory allocated to it.

绑定生命周期。

The period of time between the creation and destruction of a name-to-object binding is called the binding’s lifetime.

通过考虑以下任意函数。我会把我的问题作为评论

void foo (int j)

{ // Does i's lifetime start here?

    int i; // Or does i's lifetime start her? 

    i = j; // does binding lifetime start here?

} // i's lifetime ends

-换句话说,我的生命周期是以块“{}”开始和结束,还是以减量(int i;)开始并以“}”结束。

does i's lifetime start and end with the blocks "{ }" or start with the declaration (int i;) and end with "}".

来自 C++11 标准:

3.8 Object lifetime [basic.life]

1 The lifetime of an object is a runtime property of the object. An object is said to have non-trivial initialization if it is of a class or aggregate type and it or one of its members is initialized by a constructor other than a trivial default constructor. [ Note: initialization by a trivial copy/move constructor is non-trivial initialization. — end note ]

The lifetime of an object of type T begins when:
— storage with the proper alignment and size for type T is obtained, and
— if the object has non-trivial initialization, its initialization is complete.

The lifetime of an object of type T ends when:
— if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
— the storage which the object occupies is reused or released.

这是一个示例程序及其输出:

#include <iostream>

struct Foo
{
   Foo() : id(getNextID()) {}

   ~Foo()
   {
      std::cout << "Destroying object " << id << std::endl;
   }

   int id;

   static int getNextID()
   {
      static int nexID = 0;
      return ++nexID;
   }
};

Foo bar()
{
   throw(10);
   return Foo();
}

int main()
{
   int i = 10;         // Lifetime starts as soon as function is entered.
   try
   {
      Foo f1;          // Lifetime starts after initialization is completed.
      Foo f2 = bar();  // Lifetime does not start at all
      int k = 20;      // Lifetime starts as soon as function is entered
                       // even though it is not initialized.
   }
   catch ( ... )
   {
   }
   return 0;
}

输出:

Destroying object 1

Variable/object 生命周期和绑定时间有时可以相同。例如,当 variable/object 通过引用 传递给子例程时,您通常会看到差异。 variable/object 仍然保留它的值,但您不能再通过 name 访问它。换句话说,参数名称和传递的变量之间的时间比变量本身的生命周期更短。

01 void addOne(int &y) // y created here
02 { 
03     y = y + 1;
04 } // y is destroyed here
05  
06 int main()
07 {
08     int x = 5;
09     std::cout << "x = " << x << '\n';
10     addOne(x);
11     std::cout << "x = " << x << '\n'; //y's value is displayed here
12     return 0;
13 }

Results:
x = 5
x = 6

y 具有可变生命周期,包括 main() 和 addone(),但 y 在第 01 行和第 04 行之间具有绑定生命周期。