在return语句中取消引用的指针会发生什么? [英] What happens to a pointer dereferenced in the return statement?
本文介绍了在return语句中取消引用的指针会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是与作业相关的问题。这不是我完成的作业本身。
This is a question related to homework. It is not the homework itself, which I have completed.
这里是一个函数的一部分(我认为相关的唯一的部分)。
Here's part of a function (the only pieces that I think relevant).
double mean(double* pD, int* sz) {
double *meanPtr = new double;
*meanPtr = 0.0;
return *meanPtr; //how to deal with a memory leak in return statement? does it leak?
}
我关心最后一位。这是否会导致内存泄漏,因为我没有指向null或删除指针?
I'm concerned about the last bit. Does this result in a memory leak as I haven't pointed to null or deleted the pointer?
推荐答案
如果你需要解决正是这个问题比这样。
If you need to solve exactly this problem than do like this
double mean(double* pD, int* sz) {
double mean = 0.0;
return mean;
}
如果这只是一个例子,你需要使用指针,指针。您可以将它包装在 std :: shared_ptr
中,以防止手动内存控制。
If this is just an example and you need to use pointers, then return a pointer. You can wrap it in std::shared_ptr
to prevent manual memory control.
这篇关于在return语句中取消引用的指针会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文