函数调用中的新运算符 [英] new operator in function call
问题描述
我的问题是在函数调用内用new
运算符分配的对象会发生什么情况.
My question is what happens to the object allocated with the new
operator that is inside a function call.
一个具体的例子:我有一个私有向量pV
,我想将其发送到类foo->func(std::vector<int> *vec)
之外的对象/函数.我首先尝试写
A specific example: I have a private vector pV
which I want to send to a object/function outside of the class, foo->func(std::vector<int> *vec)
. I first tried to write
foo->func( new std::vector<int>(pV) )
但这会导致内存泄漏(当在循环内重复调用该函数时).当我专门创建一个新对象(称为函数),然后删除该对象时,整个过程正常进行,而没有内存泄漏.
but this resulted in a memory leak (when said function is called repeatedly inside a loop). When I specifically created a new object, called the function and then deleted that object, the whole thing worked, without the memory leak.
新创建的对象'expire'不会在函数返回时被删除吗?如果没有,应该如何从调用的函数内部删除对象?哪种方法更好?
Shouldn't the newly created object 'expire' and be deleted when the function returns? If not, how should I delete the object, from inside the called function? And which is the better approach?
推荐答案
用delete
分配的对象最终必须用delete
释放,否则会发生泄漏. new
的分配与函数调用无关-您可以在一个函数中使用new
创建内容,然后在另一个函数中使用delete
释放内容,而不会出现问题.
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)
}
如果您需要将 pointer 传递给函数的对象,则无需为此使用new
.您可以使用&
运算符:
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);
在这种情况下,myobj
是一个自动变量,放置在堆栈中,并在函数退出时自动删除.在这种情况下,无需使用new
.
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.
这篇关于函数调用中的新运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!