[Interest] Can QObject::tr() be used in initialization of static const QString data members? [Qt 5.5.1, Windows]

Thiago Macieira thiago.macieira at intel.com
Thu Nov 12 19:18:48 CET 2015


On Thursday 12 November 2015 15:59:06 Alejandro Exojo wrote:
> El Tuesday 10 November 2015, Thiago Macieira escribió:
> > > What's the problem with static QString?
> > 
> > There's no actual error or problem, but it's just poor coding practice.
> 
> That certainly has surprised me. If you just mean that it could be abused,
> and that it could
> 
> > It's a static non-trivial type. We avoid those in Qt, so I make the
> > recommendation to everyone, everywhere.
> 
> Maybe not exactly a QString, but:

We avoid, but we're often guilty of violating our own practices. There are 
lots of global static non-trivials in Qt.

But note the difference between a global static and a local static. I was 
referring only to global static, the ones that are outside any function. Those 
are initialised before main() and that's why they're bad.

The ones inside functions (local statics) are initialised on first use, so 
they're fine.

> > Static non-trivials imply a load-time and exit-time overhead, even if you
> > never use that variable again. Better to initialise on first use and make
> > sure  you really need to cache the result.
> 
> But that doesn't apply to the typical use of them, isn't it? I mean that if
> you go that route, you'll do it because it's used often, or you'll destroy
> them in the destructor of a long lived class because you put them as a
> member variable. For example:
> 
> class Singleton {
>     public:
>         static Singleton& instance() {
>             static Singleton instance;
>             return instance;
>         }
>
> Or:
> 
> void Foo::bar() {
>     static QLoggingCategory log("foo.bar");
>     ...
>     qCDebug(log) << "Lorem ipsum";

Those are local statics.

> Or caching the result of a call to QStandardPaths because it makes accesses
> to the disk and you only need that check once. I remember in one case where
> I did this with a static local variable, but I ended up moving it to a
> member variable instead. So more or less the same destruction point in
> time, I think.

You also have to judge whether the caching is worth it. If you need it often, 
then yes, cache it. But don't cache something that is seldomly used, because 
you'll just be occupying memory...

-- 
Thiago Macieira - thiago.macieira (AT) intel.com
  Software Architect - Intel Open Source Technology Center




More information about the Interest mailing list