2

I am getting this warning in Qt Creator:

Don't create temporary QRegularExpression objects. Use a static QRegularExpression object instead [clazy-use-static-qregularexpression]

And it's regarding the code snippet below:

QRegularExpression re("SEARCHING...",QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = re.match(frame);
if (match.hasMatch()) {

It's not obvious to me, how should I use the QRegularExpression instead?

TSG
  • 4,242
  • 9
  • 61
  • 121

2 Answers2

4

That's a clazy warning message which you can find a description of here. It's just suggesting that you don't want to keep recreating the QRegularExpression every time you enter that function because the expression is always the same. So doing something like this should work:

static QRegularExpression re("SEARCHING...", QRegularExpression::CaseInsensitiveOption);
QRegularExpressionMatch match = re.match(frame);
if (match.hasMatch()) {
JarMan
  • 7,589
  • 1
  • 10
  • 25
  • That would be less code to run and less stack used each time the function is run, but it would keep that regex in permanent storage (though only needed when the function is run). Why is that an optimization? Sounds more like a developer decision for tradeoff...unless I'm missing something – TSG Jan 31 '23 at 22:18
  • I don't consider myself an expert in that area, but I'm just letting you know what the warning is suggesting. I'm just guessing, but since clazy has a specific warning just for QRegularExpressions perhaps that's a particularly heavy object to create. Did you try it? Did the warning go away? – JarMan Jan 31 '23 at 22:27
  • 2
    You could also just suppress the warning by adding a comment at the end of that line. I think this should work: `// clazy:exclude=use-static-qregularexpression` – JarMan Jan 31 '23 at 22:37
  • I didn't realize that the compiler/ide looked for those message. Great tip! Does it turn off the warning for that line only? – TSG Feb 01 '23 at 01:46
  • Yes, it should be just for that line. – JarMan Feb 01 '23 at 13:37
0

My solution was to use Q_GLOBAL_STATIC_WITH_ARGS

I defined the global expression in the source file that I use it.

Q_GLOBAL_STATIC_WITH_ARGS(QRegularExpression, regExp, {"SEARCHING..."});

And I used like this:

auto match = regExp->match(frame);
if (match.hasMatch()) {