title: std::bad_weak_ptr exception when using shared_from_this
body: <p>The following code causes a <code>std::bad_weak_ptr</code> exception when the ctor for <code>MyCommand</code> executes but not the function <code>MyCommand::execute</code>.</p>
  
  <pre><code>class Observer
  {
  public:
      Observer(){}
      virtual ~Observer(){}
  
      virtual void update(const std::string&amp; msg) = 0;
  };
  
  class Command
  {
  public:
      Command(){}
      virtual ~Command(){}
  
      virtual void execute() = 0;
  };
  
  class MyCommand : public Command, public Observer, public std::enable_shared_from_this&lt;MyCommand&gt;
  {
  public:
      MyCommand()
      {
          // std::bad_weak_ptr exception
          std::shared_ptr&lt;Observer&gt; observer = shared_from_this();
      }
  
      virtual ~MyCommand(){}
  
  private:
      virtual void execute()
      {
          // no exception
          std::shared_ptr&lt;Observer&gt; observer = shared_from_this();
      }
      virtual void update(const std::string&amp; msg){}
  };
  
  int main(int argc, const char* argv[])
  {
      // causes std::bad_weak_ptr exception
      std::shared_ptr&lt;Command&gt; myCommand = std::make_shared&lt;MyCommand&gt;();
  
      // doesn't cause std::bad_weak_ptr exception
      myCommand-&gt;execute();
  }
  </code></pre>
  
  <p>Reading up on <code>enable_shared_from_this</code>, I know that:</p>
  
  <blockquote>
    <p>Prior to calling shared_from_this on an object t, there must
    be a std::shared_ptr that owns t.</p>
  </blockquote>
  
  <p>I need to understand why the exception is thrown in the ctor but not in the <code>execute</code> function. </p>
  
  <p>Is is something to do with the fact that the ctor has not fully executed before <code>shared_from_this</code> is called and therefore the object is not fully constructed?</p>
  
  <p>If not, what is it?</p>