How to define a static member const?

In my Test class, there is a member of the const static subtype. Usually I define this member const static as follows.

 class Test { public: class Dummy {}; private: static Dummy const dummy; }; Test::Dummy const Test::dummy; // ERROR HERE int main() { return 0; } 

When compiling this source with gcc-4.6, it gives no errors and compiles correctly.

When compiling the same source with gcc-4.4, it gives the following error: error: uninitialized const 'Test::dummy' on the marked line.

  • Is there any other way to define this variable static const?
  • Is this a limitation of gcc-4.4?
  • Is there a workaround?
+7
source share
4 answers

Say:

 Test::Dummy const Test::dummy = { }; 
+6
source

See http://gcc.gnu.org/wiki/VerboseDiagnostics#uninitialized_const (which provides an appropriate reference to the standard), as well as the GCC 4.6 release notes that say

In 4.6.0 and 4.6.1, g ++ no longer allows initialization of const-type objects by default, unless the type has a default constructor declared by the user. In 4.6.2, g ++ implements the proposed resolution of DR 253 , so initialization is enabled by default if it initializes all subobjects. Code that fails to compile can be fixed by providing an initializer, for example.

 struct A { A(); }; struct B : A { int i; }; const B b = B(); 

Use -fpermissive to allow old, inappropriate behavior.

+2
source

you can also add the default ctor to the class Dummy :

 class Dummy { public: Dummy(){} }; 

in line 4.

EDIT: It seems that gcc 4.4 cannot generate the default value for ctor for the Dummy class. Thus, the above fixes the compiler error directly.

+1
source

In gcc 4.4 use

 Test::Dummy const Test::dummy = Test::Dummy; 

Using compilers that support C ++ 11, you can use a single initialization syntax:

 Test::Dummy const Test::dummy = { }; 

But I do not think this is supported by gcc 4.4.

0
source

All Articles