什么是裸露的指针? [英] What's a naked pointer?
问题描述
观察裸指针(请参阅第一个答复),问题非常简单:
Observing Naked Pointers (see the first reply), the questions is pretty simple:
什么是裸指针?
推荐答案
以下是简单的示例:
#include <memory>
struct X { int a,b,c; };
int main()
{
std::shared_ptr<X> sp(new X);
X* np = new X;
delete np;
}
np
是指向X
类型的对象的指针-如果已动态分配(new
/malloc
)该对象,则必须delete
/free
它...简单的指针,例如np
被称为裸指针" .
np
is pointer to object of type X
- if you have dynamically allocated (new
/ malloc
) this object, you have to delete
/ free
it... simple pointer like np
is called "naked pointer".
sp
是一个持有指向托管资源的指针的对象,这意味着您可以像使用np
一样使用它,但是当不存在拥有此资源的shared_ptr
对象时,该资源就是已释放,因此您不必delete
. 智能指针负责内存管理,因此您不必;)
sp
is an object that holds a pointer to the managed resource, which means you can use it just like you would use np
, but when there are no shared_ptr
objects that own this resource, the resource is freed, so you don't have to delete
it. Smart pointers take care of memory management, so you don't have to ;)
这篇关于什么是裸露的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!