What's a naked pointer?

前端 未结 4 1636
被撕碎了的回忆
被撕碎了的回忆 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:36

    A "naked pointer" is a "plain" pointer, i.e. the thing that the Standard and whatever book on C++ call pointer. It's the usual "T *" (where T is the type of what the pointer points to).

    The "naked" terminology came on to oppose them to smart pointers, which are classes that behave in many respects as pointers (usually they overload the operators *, -> and in some cases []).

    Smart pointers are "smart" because they specify and enforce some ownership semantic, removing the "dumbness" of naked pointers: in facts naked pointers don't specify/know if they own the object they are referring to (e.g. if it must be deallocated when the pointer goes out of scope) and, even if with some naming convention it's known that some pointer owns the object if points to, the language doesn't enforce this, so, if a pointer goes out of scope and nobody manually released the pointed object (typically this happens if an exception is raised) you have a memory leak.

    Smart pointers, instead, exploit the guarantees of the type system of C++ (copy constructor, assignment operator, guaranteed calls to destructor, ...) to establish and enforce some kind of ownership (typically: strict and nontransferable, strict but can be transferable to another smart pointer, shared between several smart pointers).

    ... that being said, there are tons of discussions about smart pointers on StackOverflow and on the Internet, I'm quite sure you'll be able to find more extensive discussions on smart pointers and why using naked pointers that own objects is usually a Bad ThingTM in a modern C++ program.

提交回复
热议问题