C++ Constant structure member initialization

前端 未结 3 1411
死守一世寂寞
死守一世寂寞 2021-01-11 19:07

I\'ve a constant struct timespec member in my class. How am I supposed to initialize it?

The only crazy idea I got is to derive my own timespec

3条回答
  •  暖寄归人
    2021-01-11 19:27

    Use an initialization list with a helper function:

    #include 
    #include 
    #include 
    
    class Foo
    {
        private:
            const timespec bar;
    
        public:
            Foo ( void ) : bar ( build_a_timespec() )
            {
    
            }
        timespec build_a_timespec() {
          timespec t;
    
          if(clock_gettime(CLOCK_REALTIME, &t)) {
            throw std::runtime_error("clock_gettime");
          }
          return t;
        }
    };
    
    
    int main() {
        Foo foo;    
        return 0;
    }
    

提交回复
热议问题