Re: [問題] using function?

看板C_and_CPP (C/C++)作者 (我要加入劍道社!)時間16年前 (2009/05/04 09:20), 編輯推噓0(001)
留言1則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《xsoho ( )》之銘言: : 請問C#中有這種用法 : using (Image<Gray, Single> image = new Image<Gray, Single>(1000, 800)) : { : ... //do something here in the image : } //The image will be disposed here and memory freed : 在 C++中的話要怎麼實現呢? : 謝謝 C++ 的物件具有明確的生命週期 區域變數中的物件在離開該區域就會自動被消滅 你只要用大括號就可以定義一個 scope: { Image<Gray, Single> image(1000, 800); ... // do something here in the image } // The image will be disposed here and memory freed 如果你不希望 image 被配置在 stack 上 可以用 auto_ptr: { auto_ptr<Image<Gray,Single> > image(new Image<Gray,Single>(1000,800)); ... } // The image will be disposed here and memory freed C# 之所以會有這種用法,是因為它使用 GC 來自動回收記憶體空間,導致 programmer 無法明確控制物件何時被解構,這會讓一些仰賴 destructor 的機制 (比如說 RAII) 難以實行。因此它提供了這個功能讓 programmer 可以明確指定物件的生命週期。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 219.87.151.2

05/04 22:10, , 1F
thx
05/04 22:10, 1F
文章代碼(AID): #19_aBjqy (C_and_CPP)
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
文章代碼(AID): #19_aBjqy (C_and_CPP)