問(wèn)題描述
假設(shè)我有一個(gè)類,其中有一個(gè)靜態(tài)成員,但我沒(méi)有創(chuàng)建任何該類型的對(duì)象.靜態(tài)變量會(huì)占用內(nèi)存嗎?如果它會(huì)被占用,把它放在一個(gè)班級(jí)里有什么意義?
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?
推薦答案
沒(méi)有
靜態(tài)成員不屬于類的實(shí)例.它們甚至不會(huì)增加 1 位實(shí)例和類大小!
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
的大小完全一樣.靜態(tài)成員更像是通過(guò) A::j
訪問(wèn)的全局對(duì)象.
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 來(lái)自 C++ 標(biāo)準(zhǔn) (2003),
$9.4.2/1 from the C++ Standard (2003),
靜態(tài)數(shù)據(jù)成員不屬于一個(gè)類的子對(duì)象.有只有一個(gè)靜態(tài)數(shù)據(jù)成員的副本由所有對(duì)象共享類.
$9.4.2/3 和 7 來(lái)自標(biāo)準(zhǔn),
$9.4.2/3 and 7 from the Standard,
一旦靜態(tài)數(shù)據(jù)成員被定義,即使沒(méi)有對(duì)象它也存在已經(jīng)創(chuàng)建了它的類.
靜態(tài)數(shù)據(jù)成員被初始化并完全像非本地一樣銷毀對(duì)象 (3.6.2, 3.6.3).
正如我所說(shuō),靜態(tài)成員更像是全局對(duì)象!
As I said, static members are more like global objects!
這篇關(guān)于如果沒(méi)有創(chuàng)建該類的對(duì)象,該類的靜態(tài)成員是否會(huì)占用內(nèi)存?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!