If we want to use polymorphism in C++, normally we need to use a base interface pointer to point to an implemented class object. It is quite easy to use in normal pointer in C++. But if we use smart pointer, shared_ptr with the base class type to hold an implemented object, things going to be a little complicated.

Firstly I think it may easy going like this way:

<br />
//Point Base pointer to an implemented Derrived object<br />
//Class &quot;Derived&quot; inheritances from class &quot;Base&quot;<br />
typedef std::shared_ptr&lt;Base&gt; BasePtr;<br />
BasePtr baseptr(new Derived());<br />
//Then call baseptr-&gt;operations<br />

Principle

The principle of using smart pointer to prevent memory leak is always use a named smart pointer variable to hold the result of new

But one thing need to be noted very carefully is that, you cannot use more than ONE shared_ptr to hold the same result of new:

<br />
int* ptr = new int;<br />
shared_ptr&lt;int&gt; p1(ptr);<br />
shared_ptr&lt;int&gt; p2(ptr); //logic error<br />

Because each time we construct a shared_ptr object, the code will maintain 2 pointers in the object:
1. Type <T*> pointer to the object you new in the heap;
2. A “Smart Area” sp_count which holds the reference count of all the shared_ptr objects which hold the <T*>;

Smart Pointer
Each time you use copy constructor or use operate=, shared_ptr will make the reference count maintenance to plus 1 or minus 1; So if there are 2 shared_ptr objects hold the same T*, the pointer <T*> will be delete twice.

This is same when we deal with this pointer. But there is a solution: use shared_from_this():

<br />
#include &lt;memory&gt;<br />
#include &lt;iostream&gt;</p>
<p>struct Good: std::enable_shared_from_this&lt;Good&gt;<br />
{<br />
    std::shared_ptr&lt;Good&gt; getptr() {<br />
        return shared_from_this();<br />
    }<br />
};</p>
<p>struct Bad<br />
{<br />
    std::shared_ptr&lt;Bad&gt; getptr() {<br />
        return std::shared_ptr&lt;Bad&gt;(this);<br />
    }<br />
    ~Bad() { std::cout &lt;&lt; &quot;Bad::~Bad() called\n&quot;; }<br />
};</p>
<p>int main()<br />
{<br />
    // Good: the two shared_ptr's share the same object<br />
    std::shared_ptr&lt;Good&gt; gp1(new Good);<br />
    std::shared_ptr&lt;Good&gt; gp2 = gp1-&gt;getptr();<br />
    std::cout &lt;&lt; &quot;gp2.use_count() = &quot; &lt;&lt; gp2.use_count() &lt;&lt; '\n';</p>
<p>    // Bad, each shared_ptr thinks it's the only owner of the object<br />
    std::shared_ptr&lt;Bad&gt; bp1(new Bad);<br />
    std::shared_ptr&lt;Bad&gt; bp2 = bp1-&gt;getptr();<br />
    std::cout &lt;&lt; &quot;bp2.use_count() = &quot; &lt;&lt; bp2.use_count() &lt;&lt; '\n';<br />
} // UB: double-delete of Bad<br />

 

 Interface Design

When I was trying to design an AbstracktSocket, which can return Socket I/O Streams, users can use I/O Streams smart_ptr to receive/send message through socket, just like the “Java way”:

Main

AbstractSocketImpl implements the interface AbstractSocket, it has the getInputStream() and getOutputStream(), which will return the SocketInputStream and SocketOutputSteam. But AbstractSocketImpl holds shared_ptr of InputStream and OutputStream which implemented from AbstractSocket. SocketInputStream and SocketOutputSteam are constructed by passing AbstractSocketImpl smart_ptr into their Constructors. So when AbstractSocketImpl initialize the Socket I/O Streams, it will share this pointer. To use shared_ptr rightly, we need make AbstractSocketImpl inherit from std::enable_shared_from_this:

 

<br />
InputStreamPtr AbstractSocketImpl::getInputStream()<br />
{<br />
    if ( !inputStreamPtr )<br />
    {<br />
        inputStreamPtr = make_shared&lt;SocketInputStream&gt;(shared_from_this());<br />
    }<br />
    return inputStreamPtr;<br />
}</p>
<p>OutputStreamPtr AbstractSocketImpl::getOutputStream()<br />
{<br />
    if ( !outputStreamPtr )<br />
    {<br />
        outputStreamPtr = make_shared&lt;SocketOutputStream&gt;(shared_from_this());<br />
    }<br />
    return outputStreamPtr;<br />
}<br />

 

You may notice that the inputStreamPtr is a shared_ptr<InputStream> type, but make_shared creates a shared_ptr<SocketInputStream> object. They are not consistent, but the compiler does not returns any error on GNU Compiler and Microsoft Windows Compiler on C++11. There is a conservative way to convert the smart pointer, by using static_pointer_cast<T> or dynamic_pointer_cast<T>:

<br />
inputStreamPtr = static_pointer_cast&lt;InputStream&gt;( make_shared&lt;SocketInputStream&gt;(shared_from_this()) );<br />

 

Single-Inheritance

I have some concern about making AbstractSocketImpl inherit from std::enable_shared_from_this, why not make AbstractSocket inherit from std::enable_shared_from_this cause AbstractSocketImpl already inherits from AbstractSocket. So how to deal with the shared_from_this()? Cause the template types are different between AbstractSocket and AbstractSocketImpl.
The Solution is following:

<br />
class AbstractSocket : boost::noncopyable, public enable_shared_from_this&lt;AbstractSocket&gt; { ... }</p>
<p>class AbstractSocketImpl : public AbstractSocket<br />
{<br />
    std::shared_ptr&lt;AbstractSocketImpl&gt; shared_from_this()<br />
    {<br />
        return std::static_pointer_cast&lt;AbstractSocketImpl&gt;(AbstractSocket::shared_from_this());<br />
    }<br />
}<br />

 

Once using enable_shared_from_this, The object must be created in Heap, NOT in Stack. Because the weak_ptr in enable_shared_from_this should be initialized. Any pointer created in Stack wrapped in shared_ptr will cause Wrong Memory Access:

<br />
// AbstractSocketImpl socketImpl(address);  //----&gt; This is NOT right!<br />
AbstractSocketImplPtr socketImpl = make_shared&lt;AbstractSocketImpl&gt;(address);<br />
InputStreamPtr inputstream = socketImpl-&gt;getInputStream();<br />
OutputStreamPtr outputstream = socketImpl-&gt;getOutputStream();<br />

 

Multiple-Inheritance

There is a topic on Stackoverflow, wich describes the correct usage of multiple inheritance from enabled_share_from_this.

The first time I saw this kind of expression, I feel so strange with it:

<br />
file_buffer&lt;uint8_t&gt;::open(outputFileName, std::ios::out).then([=](streambuf&lt;uint8_t&gt; outFile) -&gt; pplx::task&lt;http_response&gt;<br />
{<br />
    *fileBuffer = outFile; </p>
<p>    // Create an HTTP request.<br />
    // Encode the URI query since it could contain special characters like spaces.<br />
    http_client client(U(&quot;http://www.bing.com/&quot;));<br />
    return client.request(methods::GET, uri_builder(U(&quot;/search&quot;)).append_query(U(&quot;q&quot;), searchTerm).to_string());<br />
})<br />

 

So what does [=] (typename pram) -> typename { } exactly mean?

It is Lambda expression in C++11. A lambda expression represents a callable unit of code. It can be thought of as an unnamed, inline function. Like any function, a lambda has a return type, a parameter list, and a function body. Unlike a function, lambdas may be defined inside a function. A lamba expression has the form:

[capture list] (parameter list) -> return type { function body }

There is a detailed description of Lambda Expression Syntax on MSDN and CPPReference , I will not explain the syntax of Lambda Expression, I would like to introduce my understanding and usage of Lambda Expression.

As my understanding, Lambda Expression creates an Object of an Unnamed Functor (NOT a Function).

A functor is pretty much just a class which defines the operator(). That lets you create objects which “look like” a function (Stackoverflow):

<br />
// this is a functor<br />
struct add_x {<br />
  add_x(int x) : x(x) {}<br />
  int operator()(int y) { return x + y; }</p>
<p>private:<br />
  int x;<br />
};</p>
<p>// Now you can use it like this:<br />
add_x add42(42); // create an instance of the functor class<br />
int i = add42(8); // and &quot;call&quot; it<br />
assert(i == 50); // and it added 42 to its argument</p>
<p>std::vector&lt;int&gt; in; // assume this contains a bunch of values)<br />
std::vector&lt;int&gt; out;<br />
// Pass a functor to std::transform, which calls the functor on every element<br />
// in the input sequence, and stores the result to the output sequence<br />
std::transform(in.begin(), in.end(), out.begin(), add_x(1));<br />
assert(out[i] == in[i] + 1); // for all i<br />

 
As we have functor so, why do you need Lambda?

I think one important feature of Lambda is, it can create Anonymous Object, it can be Run On Defined.

Java programmers must be familiar with the code when they create an anonymous class, such expression was not supported in C++.  But Lambda express in C++11 can make a similar achievement. Java Programmers can define an anonymous Thread class:

<br />
public class A {<br />
    public static void main(String[] arg)<br />
    {<br />
        new Thread()<br />
        {<br />
            public void run() {<br />
                System.out.println(&quot;blah&quot;);<br />
            }<br />
        }.start();<br />
    }<br />
}<br />

 

C++ now can directly pass a Lambda express into a function call, cause it just bass an object into that function. The grammar is different from anonymous class in Java:

<br />
void fillVector(vector&lt;int&gt;&amp; v)<br />
{<br />
    // A local static variable.<br />
    static int nextValue = 1;</p>
<p>    // The lambda expression that appears in the following call to<br />
    // the generate function modifies and uses the local static<br />
    // variable nextValue.<br />
    generate(v.begin(), v.end(), [] { return nextValue++; });<br />
    //WARNING: this is not thread-safe and is shown for illustration only<br />
}<br />

 
Programmer can directly pass a functor object with the function body expressions into a parameter, the code will run on define.