new operator in function call

谁说胖子不能爱 提交于 2019-12-04 15:17:52

Objects allocated with new must eventually be freed with delete, or there will be leaks. Allocation with new is independent of function calls - you can create something with new in one function and free it with delete in another without problems.

If you want an object that is allocated in a function and freed when the function exits, just do this:

void foo(...) {
    // some code

    MyClass myobj(...); // object allocated here
    // some more code
    return; // object freed here (or whenever function exits)
}

If you need to pass a pointer to your object to a function, you needn't use new for that either; you can use the & operator:

std::vector<int> myvec(pV);
foo->func(&myvec);

In this case myobj is an automatic variable which is placed on the stack and automatically deleted when the function exits. There is no need to use new in this case.

There is no such thing as new objects "expiring" in C++: it is not a garbage collected or reference counted language, so you are expected to manually code all memory management of objects that you allocated with new or new[].

In this particular case, you could use unique_ptr to ensure automated deletion:

for (int i = 0 ; i != 10000 ; i++) {
    std::unique_ptr<std::vector<int> > tmp = new std::vector<int>(pV);
    foo->func(tmp);
}

There is no magic here, even though it does not look like there is a delete: the call to delete is coded explicitly inside unique_ptr, so for all practical purposes it's still manual.

A better solution would be to allocate your vector in the automatic storage, and pass a pointer to foo->func:

for (int i = 0 ; i != 10000 ; i++) {
    std::vector<int> tmp(pV);
    foo->func(&tmp);
}

I think the best approach is neither. Simply pass pV itself. It will get copied (by the copy constructor) so a new vector will be created anyway. It will be automatically destroyed upon function return.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!