问题描述
我试图在 C++ 中实现一种模式,其中嵌套私有类从外部类继承,私有类通过外部抽象类中的静态工厂方法实例化。
我现在有这段代码,可以编译,但我不确定我是否正确。
搜索.h:
namespace ns_4thex {
class Search {
private:
class Implementation;
public:
static Search & create();
virtual int doIt() = 0;
};
class Search::Implementation: public Search {
int doIt();
};
}
Search.cpp:
#include "Search.h"
using namespace ns_4thex;
Search & Search::create() {
return *(new Search::Implementation());
}
int Search::Implementation::doIt() {
return 0;
}
想过吗?
解决方法
您的示例可能存在内存泄漏。工厂模式应该返回一个指针类型而不是引用类型。使用它的调用者可以释放分配的内存
Search* Search::create() {
return new Search::Implementation();
}
,
静态工厂方法总是返回一个指针类型。所以 create
函数应该返回一个指针或现代 C++ 中的智能指针。
声明:
static std::unique_ptr<Search> create();
定义:
std::unique_ptr<Search> Search::create() {
return std::make_unique<Search::Implementation>();
}
完整的代码可能是这样的:
#include <memory>
namespace ns_4thex {
class Search {
private:
class Implementation;
public:
static std::unique_ptr<Search> create();
virtual int doIt() = 0;
};
class Search::Implementation : public Search {
int doIt();
};
std::unique_ptr<Search> Search::create() {
return std::make_unique<Search::Implementation>();
}
int Search::Implementation::doIt() { return 0; }
} // namespace ns_4thex