title: C++ Smart Pointers in a Vector container
body: <p>I wrote the classic Shape Polymorphism code, but a little bit different because I'm using a Vector container and smart pointers.</p>
  
  <p>I am not a C++ expert, and I would like to know the following:</p>
  
  <ol>
  <li>Is there any memory leak?</li>
  <li>If I don't call <code>shapes.clear()</code>, is there going to be a memory leak?</li>
  <li>Is there a better way to use smart pointers and containers?</li>
  </ol>
  
  <p>Code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;memory&gt;
  #include &lt;vector&gt;
  using namespace std;
  
  class Shape {
    public:
      virtual float getArea() = 0;
      virtual ~Shape() {}
  };
  
  class Rectangle : public Shape {
    public:
      Rectangle(float w, float h) : width(w), height(h) {}
  
      float getArea() {
        return width * height;
      }
    private:
      float width;
      float height;
  };
  
  class Circle : public Shape {
    public:
      Circle(float r) : radius(r) {}
  
      float getArea() {
        return 3.141592653589793238462643383279502884 * radius * radius;
      }
    private:
      float radius;
  };
  
  void printShapeAreas(vector&lt;shared_ptr&lt;Shape&gt;&gt; &amp;shapes) {
    for(int i = 0; i &lt; shapes.size(); i++) {
      cout &lt;&lt; shapes[i]-&gt;getArea() &lt;&lt; endl;
    }
  }
  
  int main(int argc, char** argv) {
    vector&lt;shared_ptr&lt;Shape&gt;&gt; shapes;
    //this works, but you told me that is better to use make_shared
    //=============================================================
    //shapes.push_back(shared_ptr&lt;Shape&gt;(new Rectangle(10, 2)));
    //shapes.push_back(shared_ptr&lt;Shape&gt;(new Rectangle(10, 3)));
    //shapes.push_back(shared_ptr&lt;Shape&gt;(new Circle(2)));
    //shapes.push_back(shared_ptr&lt;Shape&gt;(new Circle(3)));
    //better
    //======
    shapes.push_back(std::make_shared&lt;Rectangle&gt;(10, 2));
    shapes.push_back(std::make_shared&lt;Rectangle&gt;(10, 3));
    shapes.push_back(std::make_shared&lt;Circle&gt;(2));
    shapes.push_back(std::make_shared&lt;Circle&gt;(3));
    printShapeAreas(shapes);
    shapes.clear();//If I don't call shapes.clear(), is there going to be a memory leak?
    return 0;
  }
  </code></pre>
  
  <p>Thank you :)</p>