Sharing a QLatin1String across derived classes: static const vs. inline static const
-
Hi all!
I want to share a
QLatin1String
across multiple classes derived from the same base class. I found two ways to do this:Variant 1: I declare it as
static const
insideBaseClass.h
:class BaseClass { ... protected: static const QLatin1String someString; }
and then I declare the value in
BaseClass.cpp
:#include "BaseClass.h" const QLatin1String BaseClass::someString("some string");
Variant 2: I declare the variable as
inline static const
and assign the value right inBaseClass.h
:class BaseClass { ... protected: inline static const auto someString = QLatin1String("some string"); }
For both variants, I can access the value via
BaseClass::someString
in all classes derived fromBaseClass
.I'm not sure about this. What is the right way to do it, and why?
Thanks in advance to all the C++ pros for all clarification :-)
-
The only difference is that in variant 2 the optimizer can already optimize away e.g. QLatin1String::size() or other misc functions which need the length of the string.
I doubt it makes any difference in speed here. -
-
@l3u_ said in Sharing a QLatin1String across derived classes: static const vs. inline static const:
Or is variant 1 still around because variant 2 was not possible before C++17?
correct