[Development] Views in APIs

Matthew Woehlke mwoehlke.floss at gmail.com
Wed May 13 17:41:09 CEST 2020

On 13/05/2020 03.04, Lars Knoll wrote:
> I don’t see a need to take a QStringView in those cases. With the
> exception of some low level APIs, Qt’s APIs should be safe to use. An
> overload taking a QStringView would either need to copy the data (in
> which case we could just as well only offer the QString version), or
> it holds an ‘unsecured’ pointer to the data, and lifetime is out of
> control of the class.
> The second option is something I’m only willing to accept in a very
> limited number of cases, and the API naming should make it clear that
> this is what’s happening.

I don't see a need for that.

An API that might retain a copy of a string should take a QString. An 
API that needs to *look at* a string, but will not *directly*¹ copy that 
data, should take a QStringView. If this isn't completely transparent to 
the user of the API, we're doing something wrong.

(¹ An API that must always make a deep copy, e.g. by storing a modified 
version of an input string, isn't making a "direct" copy.)

That said, you can run into issues if the implementation of the API changes.

> You might call CoW naive, but I do believe that the fact that Qt does
> use containers that own their data in most of our APIs is what makes
> Qt significantly simpler and safer to use than many other APIs.

No question. On of the projects I work with uses std::shared_ptr all 
over the place, because large data structures get passed around a lot. 
One of the developers is absolutely fanatical about avoiding deep 
copies, although I personally have not seen hard data whether this is 
merited (but my suspicion is that it is).

Shared ownership is a pain point, because users have to be careful to 
make a copy (which, due to polymorphism, is already "hard") if they need 
to change data and aren't sure if anyone else is using the data. 
Unfortunately, all this was designed before I became involved, or I 
would have insisted on Qt-style CoW value-like semantics, which would 
have made the whole mess *much* safer and easier to use.

Qt did something right. Let's please not throw that away because it 
"isn't fashionable".


More information about the Development mailing list