簡體   English   中英

為什么析構函數不是從函數中調用返回的對象?

[英]Why is the destructor not called for the returned object from the function?

我在想當一個函數將一個堆棧上的對象返回給調用函數時,調用函數會獲得原始對象的副本,但是一旦堆棧展開就會調用原始對象的析構函數。 但是在下面的程序中,析構函數只被調用一次。 我預計它會被調用兩次。

#include <iostream>

class MyClass
{
public:
  ~MyClass() { std::cout << "destructor of MyClass" << std::endl; }
};

MyClass getMyClass()
{
  MyClass obj = MyClass();
  return obj;   // dtor call for obj here?
}

int main()
{
  MyClass myobj = getMyClass();
  return 0;  // Another dtor call for myobj.
}

但“MyClass的析構函數”只打印一次。 我的假設是錯的還是還有其他事情發生在這里?

這是一種特殊情況,允許編譯器優化副本:這稱為命名返回值優化 (NRVO)。 基本上,編譯器為調用站點上的返回對象分配內存,並讓函數直接填充該內存,而不是在被調用站點創建對象並將其復制回來。 現代編譯器會盡可能地執行此操作(在某些情況下,這並不容易,因為函數中有多個返回路徑,返回不同的實例)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM