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

Exception thrown while trying to use smart pointers

本文关键字:异常 指针 智能      更新时间:2023-10-16

不久前,我正在练习设计模式,最近,我尝试实现工厂方法模式。我的朋友告诉我,我应该始终使用智能指针,所以我尝试过,但我的编译器抛出一个名为"访问冲突"的异常。我做错了什么?有一个名为"Shape"的接口,从中继承了三个类,客户端类和主函数。我尝试使用智能指针做所有事情,但我有点不确定,如果我做得对。

#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();
}

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;
}
}

也为了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();

你制作没有对象的指针 你必须写

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

或者最好使用 std::make_shared

return std::make_shared<Circle>();