简体   繁体   English

在c ++中使用unique_ptr的工厂模式

[英]Factory pattern using unique_ptr in c++

I have an old factory implementation in c++, and I want to use unique pointers instead of raw pointers in it. 我在c ++中有一个旧的工厂实现,我想在其中使用唯一指针而不是原始指针。 A minimal example of my code is as follows. 我的代码的最小示例如下。 I have a base class A , and a derived class B . 我有一个基类A和一个派生类B In main() , I pass 1 to the create method in A , and the type of b1 is now changed to B . main() ,我将1传递给Acreate方法, b1的类型现在更改为B

#include <iostream>
#include <map>

class A {
 public:
  A() {}
  virtual void Foo() {}
  std::map<int, A *> &registerType() {
    static std::map<int, A *> map_instance;
    return map_instance;
  }
  A *create(int n) { return registerType()[n]; }
};

class B : A {
 public:
  B() { registerType()[1] = this; }
  void Foo() { std::cout << "I am B!\n"; }
};

static B b0;

int main() {
  A *b1 = new A();
  b1 = b1->create(1);
  b1->Foo();

  return 0;
}

Now if I want to change raw pointers to unique pointers, I naturally get a collection of errors (the following code results in errors): 现在,如果我想将原始指针更改为唯一指针,我自然会得到一组错误(以下代码会导致错误):

#include <iostream>
#include <map>
#include <memory>

class A {
 public:
  A() {}
  virtual void Foo() {}
  std::map<int, std::unique_ptr<A>> &registerType() {
    static std::map<int, std::unique_ptr<A>> map_instance;
    return map_instance;
  }
  std::unique_ptr<A> create(int n) { return registerType()[n]; }
};

class B : A {
 public:
  B() { registerType()[1](this); }
  void Foo() { std::cout << "I am B too!\n"; }
};

static B b0;

int main() {
  std::unique_ptr<A> b1(new A());
  b1 = b1->create(1);
  b1->Foo();

  return 0;
}

The errors are: 错误是:

In member function 'std::unique_ptr<A> A::create(int)':
use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = A; _Dp = std::default_delete<A>]'
   std::unique_ptr<A> create(int n) { return registerType()[n]; }

In constructor 'B::B()':
no match for call to '(std::map<int, std::unique_ptr<A> >::mapped_type {aka std::unique_ptr<A>}) (B* const)'
   B() { registerType()[1](this); }
                               ^

So I want to know: 所以我想知道:

  1. Were unique pointers intended to be used in cases like mine? 是否有独特的指针用于像我这样的情况? (I assume the response should be yes!) (我认为答案应该是肯定的!)
  2. I need to pass this as a unique_ptr type to the registerType method. 我需要this作为unique_ptr类型传递给registerType方法。 How I can pass the ownership of the pointer to the current instance ( this keyword) to a unique_ptr ? 我如何将指向当前实例( this关键字)的指针的所有权传递给unique_ptr (If it is possible or was intended to be possible.) (如果可能或有意。)
  3. If it is a good practice to use unique pointers here, how I should implement it? 如果在这里使用唯一指针是一个好习惯,我应该如何实现它?

First of all, if someone wants to implement a factory pattern, an acceptable way of doing it with raw pointers is as follows: 首先,如果有人想要实现工厂模式,使用原始指针执行此操作的可接受方式如下:

#include <iostream>
#include <map>

class A;

class A_Factory {
 public:
  A_Factory() {}
  virtual A *create() = 0;
};

class A {
 public:
  A() {}
  static void registerType(int n, A_Factory *factory) {
    get_factory_instance()[n] = factory;
  }
  static A *create(int n) {
    A *A_instance = get_factory_instance()[n]->create();
    return A_instance;
  }
  virtual void setMyID(int n) {}
  virtual void I_am() { std::cout << "I am A\n"; }
  virtual ~A() {}

 protected:
  int MyID;
  static std::map<int, A_Factory *> &get_factory_instance() {
    static std::map<int, A_Factory *> map_instance;
    return map_instance;
  }
};

class B : public A {
 public:
  B() {}
  void Foo() {}
  void I_am() { std::cout << "I am B " << MyID << "\n"; }
  void setMyID(int n) { MyID = n; }
  ~B() {}

 private:
};

class B_Factory : public A_Factory {
 public:
  B_Factory() { A::registerType(1, this); }
  A *create() { return new B(); }
};

static B_Factory b0_factory;

void caller() {}

int main() {
  A *b1 = A::create(1);
  A *b2 = A::create(1);
  b1->setMyID(10);
  b2->setMyID(20);
  b1->I_am();
  b2->I_am();
  delete b1;
  delete b2;

  return 0;
}

A is the base class, and B is the derived one. A是基类, B是派生类。 If we pass 1 to A::create(int n) , an object of type B will be produced. 如果我们将1传递给A::create(int n) ,将生成一个B类型的对象。 The memory is managed manually and there would be no memory leak. 手动管理内存,不会发生内存泄漏。

Concerning the questions in the post: 关于帖子中的问题:

  1. YES. 是。 unique_ptr is awesome; unique_ptr太棒了; use them wherever you can! 尽可能地使用它们!
  2. With the design presented in the question, passing the ownership of this was somehow necessary. 随着问题提出的设计,传递的所有权this在某种程度上必要的。 I cannot think of a way to pass the ownership of this . 我不能想办法传递的所有权this With the design presented in the answer, it is not necessary to pass the ownership of this . 随着在回答提出的设计,没有必要通过所有权this
  3. Implement the unique_ptr in the above factory pattern as below: 在上面的工厂模式中实现unique_ptr,如下所示:
#include <iostream>
#include <map>
#include <memory>

 class A;

 class A_Factory {
 public:
  A_Factory() {}
  virtual std::unique_ptr<A> create_unique() = 0;
};

 class A {
 public:
  A() {}
  static void registerType(int n, A_Factory *factory) {
    get_factory_instance()[n] = factory;
  }
  static std::unique_ptr<A> create_unique(int n) {
    std::unique_ptr<A> A_instance =
        std::move(get_factory_instance()[n]->create_unique());
    return A_instance;
  }

  virtual void setMyID(int n) {}
  virtual void I_am() { std::cout << "I am A\n"; }
  virtual ~A() {}

 protected:
  int MyID;
  static std::map<int, A_Factory *> &get_factory_instance() {
    static std::map<int, A_Factory *> map_instance;
    return map_instance;
  }
};

 class B : public A {
 public:
  B() {}
  void Foo() {}
  void I_am() { std::cout << "I am B " << MyID << "\n"; }
  void setMyID(int n) { MyID = n; }
  ~B() {}

 private:
};

 class B_Factory : public A_Factory {
 public:
  B_Factory() { A::registerType(1, this); }
  std::unique_ptr<A> create_unique() {
    std::unique_ptr<A> ptr_to_B(new B);
    return ptr_to_B;
  }
};

 static B_Factory b0_factory;

 void caller() {}

 int main() {
  std::unique_ptr<A> b1 = std::move(A::create_unique(1));
  std::unique_ptr<A> b2 = std::move(A::create_unique(1));
  b1->setMyID(10);
  b2->setMyID(20);
  b1->I_am();
  b2->I_am();

  return 0;
}

As you can see, no manual memory management is necessary and the memory management is handled by the unique_ptr . 如您所见,不需要手动内存管理,内存管理由unique_ptr处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM