管理std容器中的抽象类

Dee*_*ewy 3 c++ c++11

经过大量研究后,我仍然不明白如何使用智能指针处理抽象类集合.

以下是我得到的错误:

error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Shape; _Dp = std::default_delete<Shape>]'
   base_ptr s = shapes.front();

error: no matching function for call to 'std::unique_ptr<Shape>::unique_ptr(Shape&)'
   shapes.push(base_ptr(b));
Run Code Online (Sandbox Code Playgroud)

通过编译最小代码来复制错误(代码可在线获得).

    #include <queue>
    #include <memory>

    class Shape {
    public:
        virtual int getPerimeter() =0;
    };

    typedef std::unique_ptr<Shape> base_ptr;

    class Circle : public Shape {
    public:
        virtual int getPerimeter() { return 1; };
    };

    class Square : public Shape {
    public:
        virtual int getPerimeter() { return 0; };
    };

    class ShapeManager {
    public:
        ShapeManager();
        void useShape() {
            if(shapes.empty())
                throw "Work stack is empty.";

            base_ptr s = shapes.front();
            s->getPerimeter();
            shapes.pop();
        }

        void submitShape(Shape &b) {
            shapes.push(base_ptr(b));
        }
    private:
        std::queue<base_ptr> shapes;
    };

    int main(int argc, char **argv) {
        ShapeManager s();
        Circle c;
        s.submitShape(c);
        s.useShape();
        return 1;
    }
Run Code Online (Sandbox Code Playgroud)

如果我声明为queueas,它可以工作,queue<Shape*>但我不想处理指针 - 意思*.

编辑,此代码编译.感谢大家.Guillaume Racicot建议的这篇文章有助于看清情况.

#include <queue>
#include <memory>

class Shape {
public:
    virtual int getPerimeter() =0;
};

typedef std::unique_ptr<Shape> base_ptr;

class Circle : public Shape {
public:
    Circle() {};
    virtual int getPerimeter() { return 1; };
};

class Square : public Shape {
public:
    virtual int getPerimeter() { return 0; };
};

class ShapeManager {
public:
    ShapeManager();
    void useShape() {
        if(shapes.empty())
            throw "Work stack is empty.";

        base_ptr s = std::move(shapes.front());
        s->getPerimeter();
        shapes.pop();
    }

    void submitShape(base_ptr b) {
        shapes.push(std::move(b));
    }
private:
    std::queue<base_ptr> shapes;
};

int main(int argc, char **argv) {
    ShapeManager s;
    base_ptr c = std::make_unique<Circle>();
    s.submitShape(std::move(c));
    s.useShape();
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*ker 6

容器分散注意力.问题是unique_ptr不可复制; 如果是的话,它就不会是唯一的.所以你可能需要添加一个调用std::move:

base_ptr s = std::move(shapes.front());
Run Code Online (Sandbox Code Playgroud)

这意味着与原始代码可能要做的事情不同; 它从容器中删除对象.如果这不是你想要的,那么std::move这不是正确的答案,而且可能unique_ptr不是正确的机制.

  • @Deewy - 没有讨论你的设计目标就不可能说.您发布了编码问题,并且有几种可能的解决方案可以解决该问题.您的设计问题可能应该作为一个单独的问题提出. (2认同)