11

I found my friend's Qt code and he uses the modulo operator on two QStrings like this:

QString result = oneString % twoString;

What does it mean?

rubenvb
  • 74,642
  • 33
  • 187
  • 332

2 Answers2

15

It's just another (more efficient) way to concatenate QStrings as described in the manual

QStringBuilder uses expression templates and reimplements the '%' operator so that when you use '%' for string concatenation instead of '+', multiple substring concatenations will be postponed until the final result is about to be assigned to a QString. At this point, the amount of memory required for the final result is known. The memory allocator is then called once to get the required space, and the substrings are copied into it one by one.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
  • I'm curious why Qt doesn't just change the `QString` implementation to use the technique for the `+` operator. Presumably, it could break existing code - any idea what kind of existing code might be broken by such a change? (note that the docs describe a macro configuration that will make it so `+` will use the the new technique, saying that it "is the most convenient but not entirely source compatible"). – Michael Burr Aug 19 '12 at 17:13
  • @MichaelBurr It's an interesting question. I searched for those macros but found no concrete example of incompatibility. – cnicutar Aug 19 '12 at 17:20
  • @MichaelBurr, `+` is `QStrings`'s operator, while `%` is external to `QString`. Replacing first with second will break binary compatibility. – Lol4t0 Aug 19 '12 at 17:45
  • 1
    @MichaelBurr: From the Qt 5.1.1 docs (though I'm sure it was in 4.8) "A more global approach which is the most convenient but not entirely source compatible, is to this define in your `.pro` file: `DEFINES *= QT_USE_QSTRINGBUILDER` and the `+` will automatically be performed as the `QStringBuilder %` everywhere." – bobbogo Sep 19 '13 at 11:47
6

It is Qt specific way of string construction. Take a look on this page.

QStringBuilder uses expression templates and reimplements the '%' operator so that when you use '%' for string concatenation instead of '+', multiple substring concatenations will be postponed until the final result is about to be assigned to a QString. At this point, the amount of memory required for the final result is known. The memory allocator is then called once to get the required space, and the substrings are copied into it one by one.

besworland
  • 747
  • 2
  • 7
  • 17