I'm working with with MS Visual Studio 2017, V. 15.9.8.
I am using the excellent JetBrains ReSharper Ultimate 2019.1.2 Build 191.0.20190603.142841. It gives me a warning at the indicated location:
#include <vector>
struct T
{
std::vector<char> m;
const char *f() const
{
static const char emptyData; // ReSharper complains here
return m.size() ? &m[0] : &emptyData;
}
};
The message is
file.h: Static local variable of type 'const unsigned char' should be initialized. This is non-standard Microsoft C++ extension.
The warning disappears if emptyData
is not const.
The warning is wrong since all static data, including constant static locals, are per the standard zero-initialized, right?
Is initialisation mandatory for local static variables? Explanation: None.
The default initialization value of a static variable is zero, even if it is not assigned, which is not the case in a local variable. It is mandatory to initialize the static variable using the static keyword in C else it will return an error.
In C++ the const keyword has been improved and you can declare real const values. That's why it has to be initialized before compiling the code. The rule is slightly different: to be used in an integral constant expression, the initialization must be visible to the compiler.
The const keyword converts nothing more but a constant. The specialty of these variables is that they need to have a value at compile time and, by default, they are static. This default value means that a single copy of the variable is created and shared among all objects.
The warning is wrong since all static data, including constant static locals, are per the standard zero-initialized, right?
It's just slightly inaccurate. There is initial zero initialisation indeed, but after that the variable is default initialised. For char
, default initialisation is no initialisation which in case of previous zero initialisation would leave the zero value intact. A pedantically correct message would be that constant objects (of this type) must not be default initialised.
The standard (latest draft says):
If a program calls for the default-initialization of an object of a const-qualified type T, T shall be a const-default-constructible class type or array thereof.
The program violates this rule and is ill-formed.
Note that until C++17 default initialisation was not allowed for any const qualified type.
I believe it's because of the const
, constants variables must be initilized, if the line is const char emptyData;
, you get an error for uninitialized const
variable, so I think it's not the static
modifier that is causing the problem.
There is a topic about this matter that seems interesting here.
Whether it is const static char emptyData;
or static const char emptyData;
the error in g++2a(GNU)
compiler is:
error: uninitialized 'const emptyData' [-fpermissive]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With