【发布时间】:2021-06-04 00:21:55
【问题描述】:
我正在尝试在 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();
};
}
搜索.cpp:
#include "Search.h"
using namespace ns_4thex;
Search & Search::create() {
return *(new Search::Implementation());
}
int Search::Implementation::doIt() {
return 0;
}
想过吗?
【问题讨论】:
-
很确定
return *(new Search::Implementation());会导致大量内存泄漏 -
@AlbertoSinigaglia 在不再需要引用时调用 delete 不是消费者的责任吗?
-
这看起来你正在尝试创建
pimpl模式,还需要学习how to use singletons in C++ -
@MooingDuck 感谢您提供有用的指针。是的,粉刺模式似乎是一项有趣的研究。我像 20 年前一样使用 C++ 编程,现在我决定获得认证。
标签: c++ factory inner-classes