作者littleshan (我要加入剑道社!)
看板C_and_CPP
标题Re: [问题] using function?
时间Mon May 4 09:20:43 2009
※ 引述《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
1F:→ xsoho:thx 05/04 22:10