[英]Using the static keyword to initialize a class, a variable vs a function in C++
假設以下代碼:
我知道 C 和 C++ 中的static
都有兩個函數。 要么在內存的Data/BSS
部分分配變量(某種全局),要么在鏈接期間使變量在同一翻譯單元或類中可見。
我的代碼注釋是否正確?
#include <iostream>
class test{
public:
static int y; // initialized in data section of memory. Has a scope till the lifetime of program, Only 1 instance during program lifetime between all class instances.
static int get(int a){ // `get` can only access other static data. You can also use this without a class instance using test::get(). No effect on memory allocation or linkage.
return y+a;
}
};
int test::y = 6; // initialized to 6 during compile time in `.data` section.
int main(){
static test t; // Using static here make the obj have a scope till the lifetime of program. No effect on memory allocation or linkage.
std::cout << t.get(1) << std::endl;
return 0;
}
差不多,但不完全。
x
和y
都在“編譯時”初始化。 無論您是內聯編寫初始化程序還是在定義上單獨編寫初始化程序都沒有關系,除了通常您必須編寫一個定義並且您目前缺少x
一個定義。 (在這個玩具示例中,您可以避免使用它,因為您沒有使用它,更一般地說,您可以使用新的inline static
功能跳過該問題!)
其余的看起來或多或少是正確的。 然而,我會警告不要專注於.data
部分和.bss
部分以及編譯時和運行時,因為這些對 C++ 來說實際上並不重要。 您真正擁有的是靜態成員變量和具有靜態存儲持續時間的局部變量。 記住並使用 C++ 術語,然后您就可以推理行為,而不是推理實際上並不重要的實現細節,除非您正在做超出 C++ 本身范圍的奇怪的低級事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.