Using boost factory to produce products on demands C++

孤者浪人 提交于 2019-12-13 07:24:40

问题


What confused me is that I don't want to create a object with a pointer like 'Product_ptr productA', are there some other methods? Another questions is that all my products use DoSomething(), but I also want to add different attributes to different products, how to achieve this? Thanks for your suggestions!!


回答1:


Generally you cannot avoid pointers in C++ when dealing with dynamically created objects. You have to manage and pass ownership for such objects which is naturally done with pointers, mainly smart pointers, of course.

Despite there are some ways to hide them, e.g. maintaining ownership of objects in some central point (factory) and pass them to consumers by reference. Such way has several drawbacks, e.g. consumer need explicitly release the object so the factory can destroy it and not waste resources. But if your objects are lightweight and their lifetime is the same as lifetime fo entire program or specific factory, this could be useful.

Example:

template <class Product>
class Factory
{
   // List elements are unaffected by insertion/deletion
   // Could be also container of smart pointers if objects need
   // to be created directly on heap
   std:list<Product> m_objects;

public:

   Product& CreateProduct()
   {
      m_objects.push_back(Product());
      return m_objects.back();
   } 

};

// Usage
Factory<MyProduct> factory;
MyProduct& prod = factory.CreateProduct();
...

This solution is possible, but has limitations, don't use it without real need. Returning appropriate smart pointer from factory, e.g. std::shared_ptr is preferable because it gives you explicit semantics on object ownership and makes code more clear, maintanable and error-proof.



来源:https://stackoverflow.com/questions/12977753/using-boost-factory-to-produce-products-on-demands-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!