在循环中创建新的指针对象
说我做这样的事情
for(int i = 0; i < 10; i++)
{
//create a pointer object using new
//use the object
}
在循环中使用指针对象后是否需要删除指针对象?我在想,如果我不删除它,它会不断创建一个新对象 10 次,然后该对象就挂在那里,吃资源.
Do I need to delete the pointer object after using it in the loop? I was thinking like, if I didn't delete it, it will keep creating a new object for 10 times and the object just hang in there after that, eating resources.
是的,对于每一个new
,都需要有一个对应的delete
.(并且每个 new[]
都有一个 delete[]
.)
Yes, for every new
there needs to be a corresponding delete
. (And a delete[]
for every new[]
.)
然而,C++ 的方式是尽可能避免动态存储,而是使用局部、自动变量强>:
However, the C++ way would be to avoid dynamic storage as much as possible and rather employ local, automatic variables:
for(int i = 0; i < 10; ++i)
{
some_class object;
//use object
} // object gets destroyed here automatically
如果您需要动态分配该对象(我对此表示怀疑,但确实存在这种情况),那么使用智能指针.一个智能指针会为你执行 delete
,无论你以何种方式离开它所属的范围:
If you need to allocate that object dynamically (which I doubt, but there are such cases), then use a smart pointer. A smart pointer will execute the delete
for you, no matter which way you leave the scope it belongs to:
for(int i = 0; i < 10; ++i)
{
smart_ptr<some_class> object(new some_class());
//use object
} // object gets destroyed here automatically
当前的标准只知道一个名为 std::auto_ptr
的智能指针,在这种情况下它可以满足您的需求.下一个标准将带来更多,其中替换了 std::auto_ptr
,名为 std::unique_ptr
,还有一个具有共享所有权语义的,名为 std::shared_ptr
.您的编译器/标准库可能实际上已经支持它们.如果没有,您可以在 boost 的众多优秀库中找到它们.
The current standard only knows one smart pointer, named std::auto_ptr
, which would would do what you need in this case. The next standard will come with several more, among them a replacement for std::auto_ptr
, named std::unique_ptr
, and one with shared ownership semantic, named std::shared_ptr
. Your compiler/std lib might actually already support them. If not, you can find them among the many great libraries to be found at boost.
顺便说一句,请注意我已经用 ++i
替换了你的 i++
.在 int
的情况下,这不会对您的场景产生任何影响,但是对于某些类型 i++
可能会创建不必要的副本.(如果你不关心效率,为什么要用 C++ 编程?)
BTW, note that I have replaced your i++
with ++i
. In case of an int
this doesn't make any difference in your scenario, but there are types for which i++
might create an unnecessary copy. (If efficiency wouldn't concern you, why program in C++?)