Как предотвратить прямой вызов конструктора и деструктора производных классов в C++C++

Программы на C++. Форум разработчиков
Ответить Пред. темаСлед. тема
Гость
 Как предотвратить прямой вызов конструктора и деструктора производных классов в C++

Сообщение Гость »


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) { ... } 
Is it possible to throw an exception or a compile error if the constructor / destructor of any class that extends Entity is called manually?

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 ...             }         } } 
I use an integer instead of a bool because the constructor of an Entity could call other constructors. I think this solution covers all cases, but let me know if there is something that I'm missing.

Edit3: Small fix in the code


Источник: https://stackoverflow.com/questions/781 ... being-call
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Соединяйте узлы с соседями по прямой видимости (прямой)
    Anonymous » » в форуме Python
    0 Ответы
    38 Просмотры
    Последнее сообщение Anonymous
  • Вызов конструктора из другого конструктора оставляет элементы данных неинициализированными [дубликат]
    Anonymous » » в форуме C++
    0 Ответы
    58 Просмотры
    Последнее сообщение Anonymous
  • «Решение наследования параметров по умолчанию в виртуальных функциях C++ производных классов?» [дубликат]
    Гость » » в форуме C++
    0 Ответы
    105 Просмотры
    Последнее сообщение Гость
  • Как применить шаблон стратегии к набору производных классов?
    Anonymous » » в форуме C++
    0 Ответы
    115 Просмотры
    Последнее сообщение Anonymous
  • Как реализовать функцию Create() для производных классов в C++
    Гость » » в форуме C++
    0 Ответы
    19 Просмотры
    Последнее сообщение Гость

Вернуться в «C++»