Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a naked pointer?

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

what is a Naked Pointer?

like image 717
mu_sa Avatar asked Feb 15 '12 18:02

mu_sa


1 Answers

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 ;)

like image 196
LihO Avatar answered Sep 28 '22 03:09

LihO