Sharing a QLatin1String across derived classes: static const vs. inline static const
-
wrote on 21 Jan 2025, 17:13 last edited by l3u_
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. -
wrote on 21 Jan 2025, 17:36 last edited by l3u_
So this is more a question of programming style? Does it have any other implication? Besides the fact that I cheap out the line of code needed in variant 1 in the cpp file? Or is variant 1 still around because variant 2 was not possible before C++17?
-
So this is more a question of programming style? Does it have any other implication? Besides the fact that I cheap out the line of code needed in variant 1 in the cpp file? Or is variant 1 still around because variant 2 was not possible before C++17?
@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
-
wrote on 21 Jan 2025, 18:07 last edited by
Well okay, then I'll go for variant 2 – seems more logical to me to declare such a shared const variable right away instead of having to re-reference it inside the implementation.
Thanks for the clarification :-)
3/5