重新分配静态变量如何工作?

How does reassigning static variables work?

既然静态变量的生命周期就是程序的生命周期,当您尝试重新分配它时究竟会发生什么?

一些如何在下面的程序中,test.loc 在被销毁之前最终变成 6,尽管构造函数是唯一可以更改该值的东西。它是原始对象本身,那么它的成员变量之一如何变化?

#include <iostream>

class Test
{
public:
   int loc = 0;

   Test()
   {
      std::cout << "Constructed!" << loc << "\n";
   }

   Test(int j)
   {
      loc = j;
      std::cout << "Constructed!" << loc << "\n";
   }

   ~Test()
   {
      std::cout << "Destroyed!" << loc << "\n";
   }
};

static Test test;


int main()
{
   // Write C++ code here

   test = Test(6);


   return 0;
}

输出:

Constructed!0
Constructed!6
Destroyed!6 // this is the locally constructed variable
Destroyed!6 // This is the static variable getting destroyed

Some how in the program below, the test.loc ends up becoming 6 before getting destroyed eventhough the constructor is the only thing that can change that value.

但这实际上就是您要更改 loc 的值所做的事情。如果我 运行 你的程序,我得到这个输出:

Constructed!0
Constructed!6
Destroyed!6
Destroyed!6

调用了两个构造函数和两个析构函数。程序一进入 main,第一个构造函数大概就会被调用,其中 test 是用不带参数的构造函数构造的。当您执行 Test(6) 时将调用第二个构造函数。这将创建一个新的 Test 对象,其 loc 设置为 6,然后将临时对象分配给 testtest 现在本质上是您创建的临时文件的副本。至于两个析构函数,一个是你创建的临时Test(6),一个是test.

您的程序未定义赋值运算符 (operator=),因此编译器会为您创建一个。该赋值运算符将从 Test 的源实例复制 [​​=12=] 的值,并将更改目标实例中 loc 的值。

如果您将以下内容添加到您的 Test class,您将看到发生了什么:

Test &operator=(const Test &src) {
    std::cout << "Assigned!" << loc << "<-" << src.loc << "\n";
    // this is what the default assigment operator does:
    loc = src.loc
}