工厂方法返回 shared_ptr 是为了实现自动内存管理、支持共享所有权和多态性,避免内存泄漏并提升代码安全性与灵活性;通过 std::make_shared 创建对象可提高性能和异常安全性,适用于多模块共享对象或生命周期不确定的场景,尤其在需要将对象存入容器或传递给回调时比 unique_ptr 更合适,但需注意避免循环引用并保证注册机制的线程安全,是现代 c++++ 中构建可扩展系统的推荐做法。

在 C++ 的工厂模式中,使用智能指针(尤其是
std::shared_ptr
std::unique_ptr
shared_ptr
shared_ptr
工厂模式的核心是将对象的创建过程封装起来,客户端无需关心具体类型,只需通过接口使用对象。返回
shared_ptr
shared_ptr<Base>
shared_ptr
假设我们有一个图形形状的基类和几个派生类:
#include <memory>
#include <string>
class Shape {
public:
virtual ~Shape() = default;
virtual void draw() const = 0;
};
class Circle : public Shape {
public:
void draw() const override {
// 绘制圆形
}
};
class Rectangle : public Shape {
public:
void draw() const override {
// 绘制矩形
}
};接下来,我们实现一个工厂类或工厂函数,返回
std::shared_ptr<Shape>
#include <map>
#include <functional>
class ShapeFactory {
public:
using Creator = std::function<std::shared_ptr<Shape>()>;
static std::shared_ptr<Shape> create(const std::string& type) {
auto it = creators().find(type);
if (it != creators().end()) {
return it->second();
}
return nullptr; // 或抛出异常
}
static void registerType(const std::string& type, Creator creator) {
creators()[type] = creator;
}
private:
static std::map<std::string, Creator>& creators() {
static std::map<std::string, Creator> instance;
return instance;
}
};注册类型并使用:
// 注册类型
ShapeFactory::registerType("circle", []() { return std::make_shared<Circle>(); });
ShapeFactory::registerType("rectangle", []() { return std::make_shared<Rectangle>(); });
// 使用工厂创建对象
auto shape = ShapeFactory::create("circle");
if (shape) {
shape->draw();
}shared_ptr
unique_ptr
虽然
unique_ptr
shared_ptr
如果你能确定对象只有一个所有者,且不会被共享,
unique_ptr
shared_ptr
使用 make_shared
new
它更高效(一次内存分配),也更安全(避免异常时的内存泄漏)。
避免循环引用:
如果对象之间存在互相引用,注意使用
weak_ptr
注册机制可扩展:
上述工厂支持运行时注册,适合插件式架构。
线程安全考虑:
如果多个线程同时调用
create
creators()
基本上就这些。返回
shared_ptr
以上就是智能指针在工厂模式中应用 返回shared_ptr的工厂方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号