什么是裸露的指针? [英] What's a naked pointer?

查看:172
本文介绍了什么是裸露的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

观察裸指针(请参阅第一个答复),问题非常简单:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆