title: Instantiate shared_ptr objects from SWIG in Python
body: <p>I have a <code>BaseClass</code> and some derived classes
  </p>
  
  <pre><code>#ifndef TEST_H__
  #define TEST_H__
  
  #include &lt;iostream&gt;
  #include &lt;memory&gt;
  
  class BaseClass
  {
    public:
    virtual double eval(double x) const = 0;
  };
  
  class Square: public BaseClass
  {
    public:
    double eval(double x) const {return x*x;}
  };
  
  class Add1: public BaseClass
  {
    public:
    Add1(BaseClass &amp; obj): obj_(obj) {}
  
    double eval(double x) const {return obj_.eval(x) + 1.0;}
  
    private:
    BaseClass &amp; obj_;
  };
  
  #endif /* TEST_H__ */
  </code></pre>
  
  <p>which are treated with SWIG à la</p>
  
  
  
  <pre><code>%module test
  
  %{
  #define SWIG_FILE_WITH_INIT
  %}
  
  %{
  #include "test.h"
  %}
  
  %include "test.h"
  </code></pre>
  
  <p>This can be used from Python like</p>
  
  
  
  <pre><code>import test
  s = test.Square()
  a = test.Add1(s)
  print(a.eval(2.0))
  </code></pre>
  
  <p>What's <em>segfaulting</em>:</p>
  
  
  
  <pre><code>import test
  a = test.Add1(test.Square())
  print(a.eval(2.0))
  </code></pre>
  
  <p>Why? The <code>test.Square()</code> is not assigned to a variable, so doesn't exist anymore after the assignment to <code>a</code>, and <code>obj_</code> points to invalid storage.</p>
  
  <p>To avoid such behavior, the idea to to use <code>std::shared_ptr&lt;BaseClass&gt;</code> instead of <code>BaseClass&amp;</code>, i.e.</p>
  
  
  
  <pre><code>class Add1: public BaseClass
  {
    public:
    Add1(std::shared_ptr&lt;BaseClass&gt; &amp; obj): obj_(obj) {}
  
    double eval(double x) const {return obj_-&gt;eval(x) + 1.0;}
  
    private:
    std::shared_ptr&lt;BaseClass&gt; obj_;
  };
  </code></pre>
  
  <p>This exact code won't work though with</p>
  
  
  
  <pre><code>TypeError: in method 'new_Add1', argument 1 of type 'std::shared_ptr&lt; BaseClass &gt; &amp;'
  </code></pre>
  
  <p>Makes sense, too: <code>test.Square()</code> doesn't return a <code>std::shared_ptr&lt;BaseClass&gt;</code> but simply a <code>Square</code> aka <code>BaseClass</code> instance.</p>
  
  <p>Is it possible to have <code>test.Square()</code> return a shared pointer <code>std::shared_ptr&lt;Square&gt;</code>?</p>