【问题标题】:Correct pattern for nested private class that inherit from outer class从外部类继承的嵌套私有类的正确模式
【发布时间】: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


【解决方案1】:

静态工厂方法总是返回一个指针类型。所以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

【讨论】:

    【解决方案2】:

    您的示例可能存在内存泄漏。工厂模式应该返回一个指针类型而不是引用类型。使用它的调用者可以释放分配的内存

    Search* Search::create() {
        return new Search::Implementation();
    }
    

    【讨论】:

    • 最好使用make_unique并返回unique_ptr以使所有权干净。
    • 所以您不能使用运算符 (&) 的地址对引用调用 delete?
    • @prehistoricpenguin 如果您将评论作为答案,我会将其作为该问题的公认答案。
    • @4thex 您的代码中的模式看起来很有趣,这是我第一次看到这种设计,您能分享一些用例吗?
    • @prehistoricpenguin 这是我在 C# 中使用的模式。我不想使用 new 并试图将实现作为参数传递,而是想基本上使这成为不可能。只有抽象类型会被传递,创建实例的唯一方法是通过工厂方法。如果需要,以后可以轻松创建替代实现。
    猜你喜欢
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    相关资源
    最近更新 更多