开发者

Creating new pointer object in loop

Say I do something like this

for(int i = 0; i < 10; i++)
{
    //create a pointer object using new
    //use the object
}

Do I need to delete the pointer object after using it in开发者_Go百科 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.


Yes, for every new there needs to be a corresponding delete. (And a delete[] for every new[].)

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 

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 

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.


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++?)


Yep.

You must delete something that you new'ed when you no longer need it, otherwise you'll get a memory leak.


Yes technically you need to delete them.

But. We have this amazing thing called smart pointers that do this auto-magically.

for(int i = 0; i < 10; i++)
{
    std::auto_ptr<int> x(new int(10));

    // automatically deleted after each iteration.
}


If you were so inclined you could use a smart pointer (something like Boost's shared_pointer) and then as soon as the pointer went out of scope for the final time the object would automatically be deleted.


Yes, you need to delete it. But doing a new/delete every iteration of the loop may not be the best option -- you need to provide more context to get better advice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜