问题
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