[英]What does the C++ standard mean regarding object lifetime begins?
在3.8.1節的n3690 C ++標准中,有以下文本:
The lifetime of an object of type T begins when:
— storage with the proper alignment and size for type T is obtained, and
— if the object has non-trivial initialization, its initialization is complete.
假設有一個用戶定義的構造函數。
最后一句話是什么意思? 是在初始化程序列表完成初始化之后還是在構造函數主體完成運行之后? 還是最后一句話意味着其他意思?
12.6.2 [class.base.init],項目6,列出了初始化步驟,這是最后一步:
最后,執行構造函數主體的復合語句 。
因此,一旦主體執行完畢,初始化就完成了。
當構造函數主體完成運行時
這個。 不能保證在構造過程中拋出的對象具有不變性,因此其壽命不會開始。 這樣的結果是析構函數將不會被調用:
#include <iostream>
struct Stillborn
{
Stillborn()
{
std::cout << "inside constructor\n";
throw 42;
}
~Stillborn()
{
std::cout << "inside destructor\n";
}
};
int main()
{
try
{
Stillborn x;
}
catch (...)
{
std::cout << "inside catch block\n";
}
}
現場演示 。 注意“內部析構函數”如何不出現在輸出中。
有一個注釋:
“ [[注意:瑣碎的復制/移動構造函數進行的初始化是非瑣碎的初始化。—尾注]
這意味着平凡的構造函數何時將完成其執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.