[Development] Recommended way to take in strings

A. Pönitz apoenitz at t-online.de
Wed May 31 21:00:23 CEST 2023


On Wed, May 31, 2023 at 07:17:21AM +0000, Marc Mutz via Development wrote:
> On 31.05.23 09:07, Sami Varanka via Development wrote:
> > What is the recommended way for functions to take strings? Our QtGraphs 
> > API takes in const QString & but is recommended way nowadays take in 
> > QAnyStringView?
> 
> I doubt there's an accepted project-wide standard, yet, but as a rule of 
> thumb that everyone might be able to agree on: If the function doesn't 
> store the string as-is (=parses or pre-processes it), take by 
> QAnyStringView, otherwise continue to take by QString cref.

Might, or not: /I/ would not make a "permanent" API dependent on how a function
is "incidentally" implemented (i.e. leak some "random" implementation detail
to the API), but what it /conceptually/ does.

If the function and all of its nested calls /conceptually/ never needs to store
the string, a view is fine. If there's a reasonable chance that at some point
one wants a copy of the thing or pass it on to a function that's unsure itself
then it's a const QString &.

> For very important APIs, there's the option to overload on
> 
> - `const QString &` and/or `QString &&`
> - QAnyStringView
> 
> In this case, the QString overloads have to be marked Q_WEAK_OVERLOAD to 
> avoid ambiguous calls with certain argument types (`const char*`, 
> `QByteArray`, etc).

Right. But additional symbols come with a price tag, too, so that's likely a
rather rare case beyond an few handful functions near corelib/tools/* or
perhaps some custom parsers...

Andre'


More information about the Development mailing list