C++ Constant structure member initialization

前端 未结 3 1407
死守一世寂寞
死守一世寂寞 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 <iostream>
    #include <time.h>
    #include <stdexcept>
    
    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;
    }
    
    0 讨论(0)
  • 2021-01-11 19:33

    Use initialization list

    class Foo
    {
        private:
            const timespec bar;
    
        public:
            Foo ( void ) :
                bar(100)
            { 
    
            }
    };
    

    If you want to initialize structure with bracers then use them

    Foo ( void ) : bar({1, 2})
    
    0 讨论(0)
  • 2021-01-11 19:39

    In C++11, you can initalise an aggregate member in the constructor's initialiser list:

    Foo() : bar{1,1} {}
    

    In older versions of the language, you would need a factory function:

    Foo() : bar(make_bar()) {}
    
    static timespec make_bar() {timespec bar = {1,1}; return bar;}
    
    0 讨论(0)
提交回复
热议问题