什么是裸指针? [英] Whats a naked pointer?
问题描述
观察裸指针(见第一个回复),问题很简单:
/ p>
什么是裸指针?
/ p>
#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
it ...简单的指针,如 np
称为裸指针。
sp
是一个包含指向托管资源的指针的对象,这意味着您可以像使用 np
一样使用它,但是当没有 shared_ptr
拥有此资源的对象,资源被释放,因此您不必 delete
。 智能指针负责内存管理,因此您不必:)
Observing Naked Pointers (see the first reply), the questions is pretty simple:
what is a Naked Pointer?
Here's simple example:
#include <memory>
struct X { int a,b,c; };
int main()
{
std::shared_ptr<X> sp(new X);
X* np = new X;
delete 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
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屋!