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
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;
}
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})
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;}