Modern C++ lacks smart pointers. There are no types in the standard library, where you can replace the declaration of a pointer variable, and still have most of your code compile.
This library aims to fix that.
Feel free to copy & tailor these smart pointers however you wish.
These are not smart pointers, because they do not implement the implicit cast operator. They should be called "lifetime managers" or "holders".
Without an implicit cast operator, you must sprinkle .get()
calls everywhere, which
pollutes a codebase and makes otherwise cheap edits expensive.
If you put implicit cast operators on ordinary workhorse data types, then the general consensus is that's evil. (and I would agree)
But to extend that logic to smart pointers? Superstition and nonsense.
(Any counter-arguments against this will invariably involve esoteric examples that never appear in ordinary code.)
Actually no, they don't. See here: http://stackoverflow.com/a/3312507
All credit to Johannes Schaub (known as "litb" on SO) who figured out how to prevent this type of misuse.
Yep, you got me. For terse syntax you must write CreateFoo(pFoo.Out())
rather than the pointer-fungible CreateFoo(&pFoo)
. Or you must write
a more long-winded code sequence:
IFoo* pFooRaw = nullptr;
CreateFoo(&pFooRaw);
pFoo.Attach(pFooRaw);
Why? It's too error-prone for a lifetime management class
to give out its member variable freely, so I didn't override operator&
.
Double-pointer out-params only tend to occur in C APIs, from factory functions. These tend to be low-frequency occurrences, whereas passing an object pointer as function argument is high-frequency. But yes, this is equivocating -- ultimately I'm just drawing the line somewhere.
Note that Microsoft's CComPtr
does implement operator&
, but the only
safeguard against misuse is a runtime assert(!p)
.
Of course! That's why nobody uses the following libraries: