Re: [問題] using function?
看板C_and_CPP (C/C++)作者littleshan (我要加入劍道社!)時間16年前 (2009/05/04 09:20)推噓0(0推 0噓 1→)留言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
05/04 22:10, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章
18
34