問題描述
假設我有一個類,其中有一個靜態成員,但我沒有創建任何該類型的對象.靜態變量會占用內存嗎?如果它會被占用,把它放在一個班級里有什么意義?
Say I have a class and I have a static member in it, but I don't create any objects of that type. Will the memory be occupied for the static variable? If it would be occupied, what is the point of putting it in a class?
推薦答案
沒有
靜態成員不屬于類的實例.它們甚至不會增加 1 位實例和類大??!
static members don't belong to the instances of class. they don't increase instances and class size even by 1 bit!
struct A
{
int i;
static int j;
};
struct B
{
int i;
};
std::cout << (sizeof(A) == sizeof(B)) << std::endl;
輸出:
1
即A
和B
的大小完全一樣.靜態成員更像是通過 A::j
訪問的全局對象.
That is, size of A
and B
is exactly same. static members are more like global objects accessed through A::j
.
在 ideone 上查看演示:http://www.ideone.com/YeYxe
See demonstration at ideone : http://www.ideone.com/YeYxe
$9.4.2/1 來自 C++ 標準 (2003),
$9.4.2/1 from the C++ Standard (2003),
靜態數據成員不屬于一個類的子對象.有只有一個靜態數據成員的副本由所有對象共享類.
$9.4.2/3 和 7 來自標準,
$9.4.2/3 and 7 from the Standard,
一旦靜態數據成員被定義,即使沒有對象它也存在已經創建了它的類.
靜態數據成員被初始化并完全像非本地一樣銷毀對象 (3.6.2, 3.6.3).
正如我所說,靜態成員更像是全局對象!
As I said, static members are more like global objects!
這篇關于如果沒有創建該類的對象,該類的靜態成員是否會占用內存?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!