From 6d6bcc7be907f4544f6d3070b17f7a85d216ff6f Mon Sep 17 00:00:00 2001 From: Peter Dimov Date: Wed, 12 Feb 2003 17:11:29 +0000 Subject: [PATCH] Some prose added. [SVN r17331] --- sp_techniques.html | 340 +++++++++++++++++++++++++++++---------------- 1 file changed, 219 insertions(+), 121 deletions(-) diff --git a/sp_techniques.html b/sp_techniques.html index 59159a2..0aad415 100644 --- a/sp_techniques.html +++ b/sp_techniques.html @@ -15,21 +15,23 @@ Using a shared_ptr to hold a pointer to an array
Encapsulating allocation details, wrapping factory functions
- Using a shared_ptr to hold a pointer to a statically allocated - object
+ Using a shared_ptr to hold a pointer to a statically + allocated object
Using a shared_ptr to hold a pointer to a COM object
- Using a shared_ptr to hold a pointer to an object with an - embedded reference count
- Using a shared_ptr to hold another shared ownership smart - pointer
+ Using a shared_ptr to hold a pointer to an object + with an embedded reference count
+ Using a shared_ptr to hold another shared + ownership smart pointer
Obtaining a shared_ptr from a raw pointer
- Obtaining a shared_ptr (weak_ptr) to this in a - constructor
+ Obtaining a shared_ptr (weak_ptr) + to this in a constructor
Obtaining a shared_ptr to this
Using shared_ptr as a smart counted handle
- Using shared_ptr to execute code on block exit
- Using shared_ptr<void> to hold an arbitrary object
- Associating arbitrary data with heterogeneous shared_ptr + Using shared_ptr to execute code on block + exit
+ Using shared_ptr<void> to hold an arbitrary + object
+ Associating arbitrary data with heterogeneous shared_ptr instances
Post-constructors and pre-destructors
Using shared_ptr as a CopyConstructible mutex lock
@@ -38,27 +40,32 @@ Weak pointers to objects not managed by a shared_ptr

Using incomplete classes for implementation hiding

-

[Old, proven technique; can be used in C]

-
+		

A proven technique (that works in C, too) for separating interface from + implementation is to use a pointer to an incomplete class as an opaque handle:

+
 class FILE;
 
 FILE * fopen(char const * name, char const * mode);
 void fread(FILE * f, void * data, size_t size);
 void fclose(FILE * f);
 
-

[Compare with]

-
+		

It is possible to express the above interface using shared_ptr, + eliminating the need to manually call fclose:

+
 class FILE;
 
 shared_ptr<FILE> fopen(char const * name, char const * mode);
 void fread(shared_ptr<FILE> f, void * data, size_t size);
 
-

Note that there is no fclose function; shared_ptr's ability to execute a custom deleter makes it unnecessary.

- -

[shared_ptr<X> can be copied and destroyed when X is incomplete.]

+

This technique relies on shared_ptr's ability to execute a custom + deleter, eliminating the explicit call to fclose, and on the fact + that shared_ptr<X> can be copied and destroyed when X + is incomplete.

The "Pimpl" idiom

-

[...]

-
+		

A C++ specific variation of the incomplete class pattern is the "Pimpl" idiom. + The incomplete class is not exposed to the user; it is hidden behind a + forwarding facade. shared_ptr can be used to implement a "Pimpl":

+
 // file.hpp:
 
 class file
@@ -77,7 +84,7 @@ public:
     void read(void * data, size_t size);
 };
 
-
+		
 // file.cpp:
 
 #include "file.hpp"
@@ -107,10 +114,17 @@ void file::read(void * data, size_t size)
     pimpl_->read(data, size);
 }
 
-

[file is CopyConstructible and Assignable.]

+

The key thing to note here is that the compiler-generated copy constructor, + assignment operator, and destructor all have a sensible meaning. As a result, + file is CopyConstructible and Assignable, + allowing its use in standard containers.

Using abstract classes for implementation hiding

-

[Interface based programming]

-
+		

Another widely used C++ idiom for separating inteface and implementation is to + use abstract base classes and factory functions. The abstract classes are + sometimes called "interfaces" and the pattern is known as "interface-based + programming". Again, shared_ptr can be used as the return type of + the factory functions:

+
 // X.hpp:
 
 class X
@@ -127,7 +141,7 @@ protected:
 
 shared_ptr<X> createX();
 
-
+		
 -- X.cpp:
 
 class X_impl: public X
@@ -156,11 +170,18 @@ shared_ptr<X> createX()
     return px;
 }
 
-

[Note protected and nonvirtual destructor; client cannot delete X; shared_ptr correctly calls ~X_impl even when nonvirtual.]

+

A key property of shared_ptr is that the allocation, construction, deallocation, + and destruction details are captured at the point of construction, inside the + factory function. Note the protected and nonvirtual destructor in the example + above. The client code cannot, and does not need to, delete a pointer to X; + the shared_ptr<X> instance returned from createX + will correctly call ~X_impl.

Preventing delete px.get()

-

[Alternative 1, use the above.]

-

[Alternative 2, use a private deleter:]

-
+		

It is often desirable to prevent client code from deleting a pointer that is + being managed by shared_ptr. The previous technique showed one + possible approach, using a protected destructor. Another alternative is to use + a private deleter:

+
 class X
 {
 private:
@@ -187,34 +208,51 @@ public:
 };
 

Using a shared_ptr to hold a pointer to an array

-

[...]

-
-shared_ptr<X> px(new X[1], checked_array_deleter<X>());
+		

A shared_ptr can be used to hold a pointer to an array allocated + with new[]:

+
+shared_ptr<X> px(new X[1], checked_array_deleter<X>());
 
-

[shared_array is preferable, has a better interface; shared_ptr has *, ->, derived to base conversions.]

+

Note, however, that shared_array is + often preferable, if this is an option. It has an array-specific interface, + without operator* and operator->, and does not + allow pointer conversions.

Encapsulating allocation details, wrapping factory functions

-

[Existing interface, possibly allocates X from its own heap, ~X is private, or X is incomplete.]

-
+		

shared_ptr can be used in creating C++ wrappers over existing C + style library interfaces that return raw pointers from their factory functions + to encapsulate allocation details. As an example, consider this interface, + where CreateX might allocate X from its own private + heap, ~X may be inaccessible, or X may be incomplete:

+
 X * CreateX();
 void DestroyX(X *);
 
-

[Wrapper:]

-
+		

The only way to reliably destroy a pointer returned by CreateX is + to call DestroyX.

+

Here is how a shared_ptr-based wrapper may look like:

+
 shared_ptr<X> createX()
 {
     shared_ptr<X> px(CreateX(), DestroyX);
+    return px;
 }
 
-

[Client remains blissfully oblivious of allocation details; doesn't need to remember to call destroyX.]

-

Using a shared_ptr to hold a pointer to a statically allocated - object

-

[...]

-
+		

Client code that calls createX still does not need to know how the + object has been allocated, but now the destruction is automatic.

+

Using a shared_ptr to hold a pointer to a statically + allocated object

+

Sometimes it is desirable to create a shared_ptr to an already + existing object, so that the shared_ptr does not attempt to + destroy the object when there are no more references left. As an example, the + factory function:

+
 shared_ptr<X> createX();
 
-

[Sometimes needs to return a pointer to a statically allocated X instance.]

-
+		

in certain situations may need to return a pointer to a statically allocated X + instance.

+

The solution is to use a custom deleter that does nothing:

+
 struct null_deleter
 {
     void operator()(void const *) const
@@ -230,22 +268,31 @@ shared_ptr<X> createX()
     return px;
 }
 
-

[The same technique works for any object known to outlive the pointer.]

+

The same technique works for any object known to outlive the pointer.

Using a shared_ptr to hold a pointer to a COM Object

-

[COM objects have an embedded reference count, AddRef() and Release(), Release() self-destroys when reference count drops to zero.]

-
+		

Background: COM objects have an embedded reference count and two member + functions that manipulate it. AddRef() increments the count. Release() + decrements the count and destroys itself when the count drops to zero.

+

It is possible to hold a pointer to a COM object in a shared_ptr:

+
 shared_ptr<IWhatever> make_shared_from_COM(IWhatever * p)
 {
     p->AddRef();
-    shared_ptr<IWhatever> pw(p, mem_fn(&IWhatever::Release));
+    shared_ptr<IWhatever> pw(p, mem_fn(&IWhatever::Release));
     return pw;
 }
 
-

[All pw copies will share a single reference.]

-

Using a shared_ptr to hold a pointer to an object with an - embedded reference count

-

[A generalization of the above. Example assumes intrusive_ptr-compatible object.]

-
+		

Note, however, that shared_ptr copies created from pw will + not "register" in the embedded count of the COM object; they will share the + single reference created in make_shared_from_COM. Weak pointers + created from pw will be invalidated when the last shared_ptr + is destroyed, regardless of whether the COM object itself is still alive.

+

Using a shared_ptr to hold a pointer to an object + with an embedded reference count

+

This is a generalization of the above technique. The example assumes that the + object implements the two functions required by intrusive_ptr, + intrusive_ptr_add_ref and intrusive_ptr_release:

+
 template<class T> struct intrusive_deleter
 {
     void operator()(T * p)
@@ -261,11 +308,16 @@ shared_ptr<X> make_shared_from_intrusive(X * p)
     return px;
 }
 
-

Using a shared_ptr to hold another shared ownership smart - pointer

-

[...]

-
-template<class P> class smart_pointer_deleter
+		

Using a shared_ptr to hold another shared + ownership smart pointer

+

One of the design goals of shared_ptr is to be used in library + interfaces. It is possible to encounter a situation where a library takes a shared_ptr + argument, but the object at hand is being managed by a different reference + counted or linked smart pointer.

+

It is possible to exploit shared_ptr's custom deleter feature to + wrap this existing smart pointer behind a shared_ptr facade:

+
+template<class P> struct smart_pointer_deleter
 {
 private:
 
@@ -281,40 +333,77 @@ public:
     {
         p_.reset();
     }
+    
+    P const & get() const
+    {
+        return p_;
+    }
 };
 
 shared_ptr<X> make_shared_from_another(another_ptr<X> qx)
 {
-    shared_ptr<X> px(qx.get(), smart_pointer_deleter< another_ptr<X> >(qx));
+    shared_ptr<X> px(qx.get(), smart_pointer_deleter< another_ptr<X> >(qx));
     return px;
 }
 
-

[If p_.reset() can throw - wrap in try {} catch(...) {} block, will release p_ when all weak pointers are eliminated.]

+

One subtle point is that deleters are not allowed to throw exceptions, and the + above example as written assumes that p_.reset() doesn't throw. If + this is not the case, p_.reset() should be wrapped in a try {} + catch(...) {} block that ignores exceptions. In the (usually + unlikely) event when an exception is thrown and ignored, p_ will + be released when the lifetime of the deleter ends. This happens when all + references, including weak pointers, are destroyed or reset.

+

Another twist is that it is possible, given the above shared_ptr instance, + to recover the original smart pointer, using + get_deleter:

+
+void extract_another_from_shared(shared_ptr<X> px)
+{
+    typedef smart_pointer_deleter< another_ptr<X> > deleter;
+
+    if(deleter const * pd = get_deleter<deleter>(px))
+    {
+        another_ptr<X> qx = pd->get();
+    }
+    else
+    {
+        // not one of ours
+    }
+}
+

Obtaining a shared_ptr from a raw pointer

-

[...]

-
+		

Sometimes it is necessary to obtain a shared_ptr given a raw + pointer to an object that is already managed by another shared_ptr + instance. Example:

+
 void f(X * p)
 {
     shared_ptr<X> px(???);
 }
 
-

[Not possible in general, either switch to]

-
+		

Inside f, we'd like to create a shared_ptr to *p.

+

In the general case, this problem has no solution. One approach is to modify f + to take a shared_ptr, if possible:

+
 void f(shared_ptr<X> px);
 
-

[This transformation can be used for nonvirtual member functions, too; before:]

-
+		

The same transformation can be used for nonvirtual member functions, to convert + the implicit this:

+
 void X::f(int m);
 
-

[after]

-
+		

would become a free function with a shared_ptr first argument:

+
 void f(shared_ptr<X> this_, int m);
 
-

[If f cannot be changed, use knowledge about p's lifetime and allocation details and apply one of the above.]

-

Obtaining a shared_ptr (weak_ptr) to this in a - constructor

-

[...]

-
+		

If f cannot be changed, but X has an embedded + reference count, use make_shared_from_intrusive + described above. Or, if it's known that the shared_ptr created in + f will never outlive the object, use a null deleter.

+

Obtaining a shared_ptr (weak_ptr) + to this in a constructor

+

[...]

+
 class X
 {
 public:
@@ -325,9 +414,11 @@ public:
     }
 };
 
-

[Not possible in general. If X can have automatic or static storage, and this_ doesn't need to keep the object alive, -use a null_deleter. If X is supposed to always live on the heap, and be managed by a shared_ptr, use:]

-
+		

[Not possible in general. If X can have automatic or static + storage, and this_ doesn't need to keep the object alive, use a null_deleter. + If X is supposed to always live on the heap, and be managed by a + shared_ptr, use:]

+
 class X
 {
 private:
@@ -345,9 +436,10 @@ public:
 };
 

Obtaining a shared_ptr to this

-

[Sometimes it is needed to obtain a shared_ptr from this in a virtual member function.]

-

[The transformations from above cannot be applied.]

-
+		

[Sometimes it is needed to obtain a shared_ptr from this in a virtual member + function.]

+

[The transformations from above cannot be applied.]

+
 class X
 {
 public:
@@ -387,8 +479,8 @@ public:
     }
 };
 
-

[Solution:]

-
+		

[Solution:]

+
 class impl: public X, public Y
 {
 private:
@@ -418,16 +510,16 @@ public:
     }
 };
 
-

[Future support planned, impl: public enable_shared_from_this<impl>.]

+

[Future support planned, impl: public enable_shared_from_this<impl>.]

Using shared_ptr as a smart counted handle

-

[Win32 API allusion]

-
+		

[Win32 API allusion]

+
 typedef void * HANDLE;
 HANDLE CreateProcess();
 void CloseHandle(HANDLE);
 
-

[Quick wrapper]

-
+		

[Quick wrapper]

+
 typedef shared_ptr<void> handle;
 
 handle createProcess()
@@ -436,8 +528,8 @@ handle createProcess()
     return pv;
 }
 
-

[Better, typesafe:]

-
+		

[Better, typesafe:]

+
 class handle
 {
 private:
@@ -451,25 +543,27 @@ public:
 };
 

Using shared_ptr to execute code on block exit

-

[1. Executing f(p), where p is a pointer:]

-
+		

[1. Executing f(p), where p is a pointer:]

+
     shared_ptr<void> guard(p, f);
 
-

[2. Executing arbitrary code: f(x, y):]

-
+		

[2. Executing arbitrary code: f(x, y):]

+
     shared_ptr<void> guard(static_cast<void*>(0), bind(f, x, y));
 
-

Using shared_ptr<void> to hold an arbitrary object

-

[...]

-
+		

Using shared_ptr<void> to hold an arbitrary + object

+

[...]

+
     shared_ptr<void> pv(new X);
 
-

[Will correctly call ~X.]

-

[Can be used to strip type information: shared_ptr<X> -> (shared_ptr<void>, typeid(X))]

-

Associating arbitrary data with heterogeneous shared_ptr +

[Will correctly call ~X.]

+

[Can be used to strip type information: shared_ptr<X> -> + (shared_ptr<void>, typeid(X))]

+

Associating arbitrary data with heterogeneous shared_ptr instances

-

[...]

-
+		

[...]

+
 typedef int Data;
 
 std::map< shared_ptr<void>, Data > userData;
@@ -482,8 +576,8 @@ userData[px] = 42;
 userData[pi] = 91;
 

Post-constructors and pre-destructors

-

[...]

-
+		

[...]

+
 class X
 {
 public:
@@ -511,8 +605,9 @@ public:
 };
 

Using shared_ptr as a CopyConstructible mutex lock

-

[Sometimes it's necessary to return a mutex lock from a function. A noncopyable lock cannot be used.]

-
+		

[Sometimes it's necessary to return a mutex lock from a function. A noncopyable + lock cannot be used.]

+
 class mutex
 {
 public:
@@ -527,8 +622,8 @@ shared_ptr<mutex> lock(mutex & m)
     return shared_ptr<mutex>(&m, mem_fn(&mutex::unlock));
 }
 
-

[Or to encapsulate it in a dedicated class:]

-
+		

[Or to encapsulate it in a dedicated class:]

+
 class shared_lock
 {
 private:
@@ -540,14 +635,15 @@ public:
     template<class Mutex> explicit shared_lock(Mutex & m): pv((m.lock(), &m), mem_fn(&Mutex::unlock)) {}
 };
 
-

[Usage:]

-
+		

[Usage:]

+
     shared_lock lock(m);
 
-

[Note that shared_lock is not templated on the mutex type, thanks to shared_ptr<void>'s ability to hide type information.]

+

[Note that shared_lock is not templated on the mutex type, thanks + to shared_ptr<void>'s ability to hide type information.]

Using shared_ptr to wrap member function calls

-

[http://www.research.att.com/~bs/wrapper.pdf]

-
+		

[http://www.research.att.com/~bs/wrapper.pdf]

+
 template<class T> class pointer
 {
 private:
@@ -592,8 +688,9 @@ int main()
 }
 

Delayed deallocation

-

[In some situations, a single px.reset() can trigger an expensive deallocation in a performance-critical region.]

-
+		

[In some situations, a single px.reset() can trigger an expensive + deallocation in a performance-critical region.]

+
 class X; // ~X is expensive
 
 class Y
@@ -608,8 +705,8 @@ public:
     }
 };
 
-

[Solution 1]

-
+		

[Solution 1]

+
 vector< shared_ptr<void> > free_list;
 
 class Y
@@ -627,8 +724,8 @@ public:
 
 // periodically invoke free_list.clear() when convenient
 
-

[Solution 2, as above, but use a delayed deleter]

-
+		

[Solution 2, as above, but use a delayed deleter]

+
 struct delayed_deleter
 {
     template<class T> void operator()(T * p)
@@ -645,8 +742,8 @@ struct delayed_deleter
 };
 

Weak pointers to objects not managed by a shared_ptr

-

Make the object hold a shared_ptr to itself, using a null_deleter:

-
+		

Make the object hold a shared_ptr to itself, using a null_deleter:

+
 class X
 {
 private:
@@ -676,12 +773,13 @@ public:
     weak_ptr<X> get_weak_ptr() const { return this_; }
 };
 
-

When the object's lifetime ends, X::this_ will be destroyed, and all weak pointers will automatically expire.

+

When the object's lifetime ends, X::this_ will be destroyed, and + all weak pointers will automatically expire.


$Date$

- Copyright © 2003 Peter Dimov. Permission to copy, use, modify, sell and + Copyright © 2003 Peter Dimov. Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.