What's a naked pointer?

前端 未结 4 1664
被撕碎了的回忆
被撕碎了的回忆 2021-01-07 23:05

Observing Naked Pointers (see the first reply), the questions is pretty simple:

what is a Naked Pointer?

4条回答
  •  爱一瞬间的悲伤
    2021-01-07 23:40

    Here's simple example:

    #include 
    
    struct X { int a,b,c; };
    
    int main()
    {
        std::shared_ptr 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 ;)

提交回复
热议问题