![](/img/trans.png)
[英]Why does copy initializaton require destructor in C++17 with guaranteed move/copy elision?
[英]In the absence of copy elision, is the copy/move constructor guaranteed to be called before the destructor?
標題說的差不多。 考慮以下示例:
MyClass func()
{
MyClass myInstance;
return myInstance;
}
int main()
{
auto myInstance = func();
}
在沒有復制省略的情況下,是否可以確保在析構函數之前調用MyClass
的copy或move構造函數,因為對func()
的調用返回myInstance
? 我想象像std::shared_ptr
這樣的類在按值返回時會利用這樣的屬性。
另外,依靠這種行為有什么陷阱嗎?
是。
從[stmt.return] / 3:
返回實體的復制初始化在返回語句的操作數建立的全表達式結束時在臨時變量銷毀之前進行排序,而該操作數又在銷毀局部變量(6.6)之前進行排序。包含return語句的塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.