I'm trying to create static, constant member for a class. For now, I have this function based on C# way:
class Question : public QObject
{
Q_OBJECT
friend class Answer;
public:
static const QMap<QString /*name*/, QPair<QList<quint8> /*data*/, qint32 /*answerSize*/>> questionMap()
{
return {
{
"check digit",
{
{
0xF0, 0xC0, 0x4F
},
3
}
},
{
"line detect",
{
{
0xF0, 0xE0, 0x2F
},
79
}
}
};
}
static const Question& createQuestion(const QString& questionName) {
Question* question = new Question(questionName,
Question::questionMap()[questionName].first,
Question::questionMap()[questionName].second);
return *question;
}
I wish to have something more like this:
static const QMap<QString /*name*/, QPair<QList<quint8> /*data*/, qint32 /*answerSize*/>> questionMap =
{
{
"check digit",
{
{
0xF0, 0xC0, 0x4F
},
3
}
},
{
"line detect",
{
{
0xF0, 0xE0, 0x2F
},
79
}
}
};
as I'm not sure how the first approach looks in terms of memory management... is this function called only once and there is no difference between two ideas or the object returned from the first function is created over and over again and it's more efficient to use the second approach? Anyway, when I'm trying to use value, it goes:
field initializer is not constant
in-class initialization of static data member of non-literal type
non-constant in-class initiualization invalid for static member
(an out of class initialization is required)
cannot be initialized by a non-constant expression when being decalred
And, of course, it works when I move the initializer out of class but... why exactly? And is there a way to go around it? Should I go around it? What's the most proper way of having this value handy?