看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《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
xsoho:thx 05/04 22:10