New statement in function call

My question is what happens to the object selected by the statement newthat is inside the function call.

A concrete example: I have a particular vector pV, which I want to send the object / function outside the class foo->func(std::vector<int> *vec). I first tried to write

foo->func( new std::vector<int>(pV) )

but this led to a memory leak (when the specified function is repeatedly called inside the loop). When I deliberately created a new object called a function and then deleted this object, all the work worked without a memory leak.

Should the new object expire and be deleted when the function returns? If not, how do I remove an object from within the called function? And what is the best approach?

+2
source share
3 answers

Objects allocated with help newmust be freed with help deleteor there will be leaks. Highlighting with newis independent of function calls - you can create something with newin one function and release it with help deletein another without any problems.

If you need an object allocated in the function and freed when you exit the function, simply do the following:

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 an object in a function, you do not need to use newthis; you can use the operator &:

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

In this case myobj, it is an automatic variable that is pushed onto the stack and is automatically deleted when it exits. In this case, there is no need to use new.

+2

++ , "expires": , , new new[].

unique_ptr :

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

, delete: delete unique_ptr, .

foo->func:

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

, , . pV. ( ), . .

+2
source

Source: https://habr.com/ru/post/1652341/


All Articles