且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

调用实例构造函数时的静态类和内存分配

更新时间:2023-11-13 14:02:28

^ ]
这应该有助于了解什么是静态类
Static Classes and Static Class Members (C# Programming Guide)[^]
That should help understand what static classes are


可以给出许多聪明的答案,但是关于第一个答案的本质很简单:在关键字中添加关键字static的唯一目标一个类正是这样:禁用其实例的创建.没有任何特殊的机制,这只是语法.

您可以谈论它的目的.这只是理智.如果类具有非静态成员,则可以创建其实例,但几乎没有用.将类本身声明为静态只是防止创建类的另一种保护措施.另外,如果一个类已经声明为静态的,则编译器将阻止意外添加非静态成员.

分配…您知道,关于确定任意静态类的分配,您无能为力.假设您创建一个仅包含值类型成员的静态类.在这种情况下,什么都没有分配",静态数据段的内存将被静态地使用.但是现在,静态类只能具有静态成员,但是任何成员都可以属于任何类,并且这些类可能不是静态的.并且它们的成员可以是值类型或引用类型的静态或非静态,因此可以在堆上分配某些内存.

最后一个问题.调用实例构造函数时,将创建该类的新实例.实例的引用已分配给右侧的变量(如果有).它可能不存在,因为构造函数调用可能仅出于其副作用而完成;在这种情况下,该实例可能是垃圾收集的主题,也可能不是.在没有丢失此引用的情况下,可能会发生(非常不寻常)的情况,因为在构造函数的主体执行之前创建了"this"引用,并且可以将其分配给类范围之外的其他类型成员或变量.我已经在最近的解决方案中为您提供了其他详细信息,请参阅实例类构造函数称为 [ ^ ].

—SA
Many clever answers can be given, but the essence of things about first answer is very simple: the only goal of adding of a keyword static to a class is exactly this: to disable creation of its instance. There is no any special mechanism, this is just syntax.

You can talk about the purpose of it. This is just sanity. If a class has non-static members, creating of its instance is possible but pretty much useless. Claiming the class itself as static is just an additional safeguard to prevent creation of class. Also, if a class is already declared static, adding non-static members accidentally will be prevented by a compiler.

Allocation… You see, you cannot say anything about certain about allocation of the arbitrary static class. Suppose you create a static class with only the members of value types. In this case, nothing is "allocated", the memory of the static data segment will be used — well, statically. But now, the static class can have only the static members, but any of the members can be of any class, and that classes may be not static; and their members can be static or not static, of value types or reference types, so some of the memory can be allocated on heap.

Last question. When an instance constructor is called, a new instance of the class is created. The reference of the instance is assigned to the variable on right, if any. It may not exist as the constructor call could be done just for its side effect; in this case the instance may or may not be a subject of Garbage Collection. There can be (pretty unusual) case when this reference is not lost, as "this" reference is created before the body of the constructor is executed, and it can be assigned to some other type member or variable outside of the class scope. I already provided you with other detail in my recent solution, see memory allocation when instance class constructor is called[^].

—SA