代码之家  ›  专栏  ›  技术社区  ›  mozcelikors

以前未调用函数时给出错误

  •  0
  • mozcelikors  · 技术社区  · 7 年前

    我试图在基于C++的应用程序中管理初始化函数。我想:

    • 确保 init_some_hw_peripherals() (见下文)仅运行一次,即使 init() 多次调用。

    • 阻止函数 doPerform() 如果另一个函数 初始化某些硬件外围设备() 以前不是从对象调用的。

    我想到了以下解决方案,但它不起作用(如果没有初始化,我不会收到任何错误消息)。我知道它为什么不起作用,而且很有道理。但我想用这些类型的定义来实现我提到的。我希望这些信息能有所帮助。

    如果你能帮我处理这种情况并给我一些指导,我将不胜感激。

    提前谢谢。

    初始化

    void myClass::init(void)
    {
    #ifndef MY_INIT_
    #define MY_INIT_
          init_some_hw_peripherals();
    #endif
    }
    

    应用

    void myClass::perform (void)
    {
    #ifndef MY_INIT_
    #error "You havent initialized. Use myClass::init()"
    #else
          doPerform();
    #endif
    }
    

    编辑 :我使用私有变量的问题是,我有几个类可以调用init函数。所以我不想让它成为一个私有变量。这就是为什么我坚持使用这种解决方案,因为我知道它最初不会起作用。

    2 回复  |  直到 7 年前
        1
  •  2
  •   dbush    7 年前

    您可以使用private member告诉您初始化是否完成:

    class myClass {
    public:
        myClass() : isInit(false) {}
        ...
    private:
        bool isInit;
    };
    
    void myClass::init(void)
    {
        if (!init) {
          init_some_hw_peripherals();
          init = true;
        }
    }
    
    void myClass::perform (void)
    {
        if (!init) {
            cout << "You havent initialized. Use myClass::init()";
        } else {
          doPerform();
        }
    }
    
        2
  •  0
  •   user7860670    7 年前

    通常情况下 init -like函数表示缺少适当的构造函数。给定的要求清楚地导致了两个具有专用构造函数的类:

    class hwPeripherals
    {
          private: static ::std::atomic_bool s_construction_attempted;
    
          // instead of init_some_hw_peripherals
          public: hwPeripherals(void)
          {
              // Check that no attempts of hwPeripherals construction happened yet.
              if(s_construction_attempted.exchange(true))
              {
                   // Throw an exception.
              }
              // Initialization... Throw an exception if fails.
          }
    };
    
    class myClass
    {
         private: myClass(void) = delete;
    
         // instead of init
         public: explicit myClass(hwPeripherals & peripherals)
         {
              // Initialization... Throw an exception if fails.
         }
    
         public: void perform(void);
    };
    

    这种调用perform用户的方法需要实例化 myClass 首先,为了做到这一点,用户需要实例化 hwPeripherals :

    hwPeripherals peripherals{};
    myClass obj{peripherals};
    obj.perform();