Assuming one is never odr-used, is there a benefit of declaring a static const
or static constexpr
data member with an initializer over declaring and then defining one later? Is there a benefit to not needing a definition?
First, note that you can't define a static const
data member where you declare it. The declaration doesn't become a definition no matter what you do (such as providing an initializer). However, a static constexpr
data member doesn't need a definition, and the static const
data member of integral type with initializer doesn't need a definition if it's never ODR-used.
ODR: the One Definition Rule , in the C++11 standard §3.2 [basic.def.odr].
Providing a definition is non-trivial in a header file – for a non-template class the direct approach would lead fast to violations of the ODR, with the linker complaining. Thus a benefit of not defining is that it makes it easy to use header-only modules. And a benefit of defining is that it makes it easy to use any type whatsoever, and supports ODR-use.
There are already a host of SO questions dealing with practical solutions to the requirement of definition for ODR use, with respect to header-only modules.
The ODR has a special exemption for templates for this, and that's the basis of one practical solution. Just provide the definition in a class template, and use a dummy argument to instantiate the template. Another practical solution is to place the definition in a function, essentially a Meyers' singleton.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.