I have an abstract class "Entity". I want to prevent manual calls to the constructor and destructor of its derived classes.
To create and destroy the instances of this class, I use the following function:
Код: Выделить всё
template && std::is_constructible_v>> T* SpawnEntity(Args&&... args) { T* instance = new T(std::forward(args)...); // ... perform other operations ... return instance; } void Destroy(Entity* entity) { ... }
Edit1: I cannot control all the derived classes of Entity, so I cannot define the constructors as private.
Edit2: My main goal is to prevent other programmers (and myself) from making mistakes. I couldn't find a way to prevent the constructors and destructors from being called directly, but I found a solution where I can print a warning message if the factory class isn't used:
Код: Выделить всё
class EntityFactory { private: static inline int s_FactoryUsageDepth = 0; friend class Entity; public: template && std::is_constructible_v>> static T* SpawnEntity(Args&&... args) { s_FactoryUsageDepth++; T* instance = new T(std::forward(args)...); // ... perform other operations ... return instance; } static void Destroy(Entity* entity) { s_FactoryUsageDepth++; delete entity; // ... perform other operations ... } } class Entity { protected: Entity() { if (EntityFactory::s_FactoryUsageDepth-- == 0) { // ... show an error message ... } } virtual ~Entity() { if (EntityFactory::s_FactoryUsageDepth-- == 0) { // ... show an error message ... } } }
Edit3: Small fix in the code
Источник: https://stackoverflow.com/questions/781 ... being-call