尝试使用智能指针时引发异常

时间:2020-07-06 16:56:11

标签: c++ exception design-patterns smart-pointers

不久前,我正在练习设计模式,最近,我尝试实现了Factory Method模式。我的朋友告诉我,我应该始终使用智能指针,因此我已经尝试过了,但是我的编译器抛出了一个异常,称为“访问冲突”。我究竟做错了什么?有一个名为“ Shape”的接口,其中三个继承类,即Client类和main函数。我已经尝试使用智能指针来做所有事情,但是我不确定我是否做得正确。

#include <iostream>
#include <memory>

class Shape
{
public:
    virtual void printShape() = 0;
    static std::shared_ptr<Shape> Create(int num);
};

class Triangle : public Shape
{
public:
    virtual void printShape()
    {
        std::cout << "This is Triangle. \n";
    }
};

class Circle : public Shape
{
public:
    virtual void printShape()
    {
        std::cout << "This is Circle. \n";
    }
};

class Rectangle : public Shape
{
public:
    virtual void printShape()
    {
        std::cout << "This is Rectangle. \n";
    }
};

class Client
{
private:
    std::shared_ptr<Shape> shape;
public:
    Client()
    {
        shape=Shape::Create(1);
    }
    std::shared_ptr<Shape>getShape()
    {
        return shape;
    }
};

std::shared_ptr<Shape> Shape::Create(int num)
{
    switch (num)
    {
    case 1:
        return std::shared_ptr<Circle>();
        break;
    case 2:
        return std::shared_ptr<Triangle>();
        break;
    case 3:
        return std::shared_ptr<Rectangle>();
        break;
    }
}

int main()
{
    std::shared_ptr<Client> client;
    std::shared_ptr<Shape> shape = client->getShape();
    shape->printShape();
}

2 个答案:

答案 0 :(得分:6)

return std::shared_ptr<Circle>();这样的return语句仅返回一个空的std::shared_ptr,其中不包含任何内容。像shape->printShape();这样的取消引用会导致UB。

您应该构造一个对象,并使其由std::shared_ptr管理。例如

std::shared_ptr<Shape> Shape::Create(int num)
{
    switch (num)
    {
    case 1:
        return std::make_shared<Circle>();
        break;
    case 2:
        return std::make_shared<Triangle>();
        break;
    case 3:
        return std::make_shared<Rectangle>();
        break;
    }
}

还有client

std::shared_ptr<Client> client = std::make_shared<Client>();

或者只是

Client client; // it seems no need to use shared_pointer for client
std::shared_ptr<Shape> shape = client.getShape();

答案 1 :(得分:2)

您创建没有对象的指针 你必须写

return std::shared_ptr<Circle>(new Circle());

或者更好地使用std :: make_shared

return std::make_shared<Circle>();