如何知道指针是否指向堆或堆栈? [英] How to know if a pointer points to the heap or the stack?
本文介绍了如何知道指针是否指向堆或堆栈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例:
bool isHeapPtr(void* ptr)
{
//...
}
int iStack = 35;
int *ptrStack = &iStack;
bool isHeapPointer1 = isHeapPtr(ptrStack); // Should be false
bool isHeapPointer2 = isHeapPtr(new int(5)); // Should be true
/* I know... it is a memory leak */
< h2>为什么,我想知道这一点:
如果我有一个类中的成员指针,我不知道指针对象是否是新分配的。然后我应该使用这样的实用程序知道我是否需要 delete
指针。
我的设计尚未完成。所以,我将这样编程,我总是有 delete
它。我要避免垃圾编程
But:
My design isn't made yet. So, I will program it that way I always have to delete
it. I'm going to avoid rubbish programming
推荐答案
没有办法这样做 - 如果你需要做,是你的设计有问题。有关为什么您无法在更有效的C ++ 中进行此操作的讨论。
There is no way of doing this - and if you need to do it, there is something wrong with your design. There is a discussion of why you can't do this in More Effective C++.
这篇关于如何知道指针是否指向堆或堆栈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文