title: Return new instance or itself as std::shared_ptr rather than raw pointer
body: <p>I implemented CSS-like selector system that can be used in some object tree. My selectors are not perfectly optimal at the time of creation. Sometimes, it is possible to replace more complex selector with simple one, which is a different class type.</p>
  
  <p>I added this method to my selector interface:</p>
  
  <pre><code>virtual std::shared_ptr&lt;Selector&gt; optimize(std::shared_ptr&lt;Selector&gt; target) const = 0;
  </code></pre>
  
  <p>But there's a problem - if the selector cannot be optimized into some simpler class, it should return itself. For example, I have a selector that maintains list or items. If there is only one item, this selector is redundant and should return simpler selector, otherwise, it should return self.</p>
  
  <pre><code>std::shared_ptr&lt;Selector&gt; CSSChainedSelector::optimize() const
  {
      if(sub_selectors.size()==1) {
          return sub_selectors[0]-&gt;optimize();
      }
      else if(sub_selectors.empty()) {
          return std::shared_ptr&lt;Selector&gt;(new InvalidSelector());
      }
      else {
          //THIS WILL CAUSE MEMORY ERROR IN THE FUTURE!!!
          return std::shared_ptr&lt;Selector&gt;(this);
      }
  }
  </code></pre>
  
  <p>You mustn't create <code>shared_ptr</code> from this though. If you do, you cause the object to be deleted twice. Shared pointer must only be created from new instances. Knowing this, I had to change my design, which is now kinda crazy:</p>
  
  <pre><code>std::shared_ptr&lt;Selector&gt; CSSChainedSelector::optimize(std::shared_ptr&lt;Selector&gt; target) const
  {
      if(target.get() != this)
          return target;
      // this is probably redundant
      std::shared_ptr&lt;CSSChainedSelector&gt; self = std::dynamic_pointer_cast&lt;CSSChainedSelector&gt;(target);
      if(self) {
          if(chain_.length() == 1) {
              return chain_[0]-&gt;optimize(chain_[0]);
          }
      }
      else
          return target;
      return target;
  }
  </code></pre>
  
  <p>This requires me to call the method like this:</p>
  
  <pre><code>std::shared_ptr&lt;Selector&gt; selector(new CSSChainedSelector);
  // parsing happens
     ... some parsing ...
  selector = selector-&gt;optimize(selector);
  </code></pre>
  
  <p>This makes some sense since <code>optimize</code> method can only be called if you see the class from the outside (it doesn't change the class). Optimizations that change the class can be done during parsing.</p>
  
  <p>But is there a way to safely return shared pointer on class's own instance?</p>
  
  <p><strong>Note:</strong> The optimization described above looks like microoptimalization, because I have strongly simplified the problem. Please focus on the topic of "returning own instance as shared pointer".</p>