尝试使用智能指针时引发异常
Exception thrown while trying to use smart pointers
不久前,我正在练习设计模式,最近,我尝试实现工厂方法模式。我的朋友告诉我,我应该始终使用智能指针,所以我尝试过,但我的编译器抛出一个名为"访问冲突"的异常。我做错了什么?有一个名为"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>();
相关文章:
- 尝试使用智能指针时引发异常
- 获取指向派生类的指针在 C++ 中以运行时异常结束
- C++指针算术:对齐异常 (0x801)
- 如何避免自定义 STL 向量类的智能指针 delete[] 异常?
- free():在有效指针异常中-使用流读取巨大文件时
- 封送指向结构异常"cannot Read or Write protected memory"的指针数组的指针数组
- 将一个数组复制到函数内的另一个数组时的运行时指针异常
- dynamic_cast指针异常捕获
- 动态指针引用数组由三元运算符返回值,但有异常
- 异常未手动 - 这是空指针C++
- 启用优化时的堆栈指针比较异常
- 构造函数中的异常:init() 方法、指针、大型 try/catch 或
- 异常包括字符指针和整数指针
- 智能指针和构造函数异常
- 在Linux/GCC下,将NULL指针访问转换为C++异常
- 指向矩阵的指针在 c++ 中引发异常
- 函数指针中的C 异常规范
- 在OpenCV中调用stereoRectify会导致异常:帧指针无效
- 可以通过异常指针"duplicated"异常吗?
- 为什么在抛出异常指针时要通过引用使用 catch