尝试使用智能指针时抛出异常

Tho*_*vas 2 c++ design-patterns exception smart-pointers

不久前,我正在练习设计模式,最近,我尝试实现工厂方法模式。我的朋友告诉我应该总是使用智能指针,所以我已经尝试过了,但是我的编译器抛出了一个名为“访问冲突”的异常。我究竟做错了什么?有一个名为“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();
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 6

return 语句就像return std::shared_ptr<Circle>();只返回一个空的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

并且对于client.

std::shared_ptr<Client> client = std::make_shared<Client>();
Run Code Online (Sandbox Code Playgroud)

要不就

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