小编Emm*_*oya的帖子

Vector容器中的C++智能指针

我编写了经典的Shape Polymorphism代码,但有点不同,因为我使用的是Vector容器和智能指针.

我不是C++专家,我想知道以下内容:

  1. 有内存泄漏吗?
  2. 如果我不打电话shapes.clear(),会不会有内存泄漏?
  3. 有没有更好的方法来使用智能指针和容器?

码:

#include <iostream>
#include <memory>
#include <vector>
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 * …
Run Code Online (Sandbox Code Playgroud)

c++ polymorphism smart-pointers stdvector

4
推荐指数
2
解决办法
4017
查看次数

标签 统计

c++ ×1

polymorphism ×1

smart-pointers ×1

stdvector ×1