template <typename T> // custom delete function
void arrayDeleter(T *ptr, void *cookie)
{ delete [] ptr; }
...
using BloombergLP::bslma::ManagedPtr;
// a shared pointer to an array, with custom deleter, and cookie is an argument for deleter
ManagedPtr<Bond> guard(new Bond[10], NULL,&arrayDeleter<Bond>);
// on clean-up the custom deleter is called
#include <bsl_memory.h>
class C {}
bsl::shared_ptr<C> p(new C(arg1, arg2));
bsl::shared_ptr<C> q;
bsl::shared_ptr<C> r = bsl::make_shared<C>(arg1, arg2); // without using new, preferred way
C *rawPtr = new C();
bsl::shared_ptr<C> p(rawPtr);
bsl::shared_ptr<C> q(rawPtr);
Moral: Don’t use the same raw pointer to initialize two shared pointers, Avoid having both shared pointers and raw pointers pointing to the same object
class C {
bsl::shared_ptr<C> d_next;
...
};
bsl::shared_ptr<C> p(new C);
bsl::shared_ptr<C> q(new C);
bsl::shared_ptr<C> r(new C);
p->setNext(q);
q->setNext(r);
r->setNext(p);
p.reset();
q.reset();
r.reset();
bsl::shared_ptr<Bond> b = bsl::make_shared<Bond>(…);
bsl::weak_ptr<Bond> weakb(b); // create a weak pointer to b
bsl::shared_ptr<Bond> tempb = weakb.lock();
// convert to shared pointer to access/use it
tempb.reset(); // finished, usually just goes out of scope
b.reset(); // release original shared pointer
if (weakb.expired()) {
// weak pointer is expired when target shared pointer
// has been deleted
bsl::cout << "GONE!\n";}