[Development] Best practice for defining an integer constant
Thiago Macieira
thiago.macieira at intel.com
Fri Feb 14 18:03:26 CET 2014
Em sex 14 fev 2014, às 15:59:28, Mandeep Sandhu escreveu:
> I have a need for defining an integer constant that'll be used for
> initializing a member variable of a private class.
>
> The Qt coding conventions (http://qt-project.org/wiki/Coding-Conventions)
> recommend using an enum over 'const int'.
>
> The rationale given there is that an enum will be replaced at compile-time
> resulting in 'faster code'. Won't that be the case with 'const int' as
> well? I think a 'const int' will be inlined in the code. CMIIW.
That is the case, *except* if you pass it via const-ref. If you do that, then
ODR kicks in and you need to have the variable defined somewhere.
For variables in the file scope, the declaration is the definition, so it's not
a problem. For variables in a class scope, the static const declaration is
*not* the definition.
Try it:
struct Foo
{
static const int Max = 128;
};
void f()
{
QHash<int, QString> hash;
hash.insert(Foo::Max, "Max");
}
Hint:
iterator insert(const Key &key, const T &value);
(const ref for the key)
--
Thiago Macieira - thiago.macieira (AT) intel.com
Software Architect - Intel Open Source Technology Center
More information about the Development
mailing list