[英]static variable construction in C++
編譯器如何知道如何正確處理此代碼?
struct Foo
{
int bar;
Foo()
{
bar = 3;
}
Foo& operator=(const Foo& other)
{
bar = other.bar;
return *this;
}
int SetBar(int newBar)
{
return bar = newBar;
}
};
static Foo baz;
static Foo someOtherBaz = baz;
static int placeholder = baz.SetBar(4);
someOtherBaz.bar
的最終價值是多少?
someOtherBaz.bar
的值為3。
翻譯單元內的靜態對象按照它們在TU中出現的順序構造(注意,在不同的翻譯單元中沒有靜態對象的定義順序)。
baz
。 這會將baz.bar
設置為3。 someOtherBaz
。 由於沒有定義復制構造函數,因此將使用默認的復制構造函數,它只復制每個字段。 因此someOtherBaz.bar
將被賦予值3。 placeholder
,將調用baz.SetBar
,它也將改變baz
的值(但不是someOtherBaz
因為它們是獨立的對象;當你根據baz
的值創建someOtherBaz
,它們是不同的對象,因此可以獨立更改) 。 所以,最后,你將擁有:
baz.bar: 4
someOtherBaz.bar: 3
placeholder: 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.