Besides the others' cases, it works in the following cases:
MyClass a[10];
MyClass* b = new MyClass[10];
Be careful if you use STL containers to hold MyClass
objects. It may not behave the same as you expected, and the problem is hard to find. See the following example:
int MyClass::currentID = 0;
...
std::vector<MyClass> c(10);
MyClass a;
In this case, The result is the following:
c[0].myID = 0;
c[1].myID = 0;
....
c[9].myID = 0
=============
a.myID = 1.
The default constructor is executed only ONE time. The reason is that the constructor of std::vector will use the same value to initial all the element of the vector. In my system, the constructor of std::vector is the following:
explicit
vector(size_type __n, const value_type& __value = value_type(),
const allocator_type& __a = allocator_type())
: _Base(__n, __a)
{ _M_fill_initialize(__n, __value); }
_M_fill_initialize
will initialize the memory allocated using __value
(which comes from default constructor value_type()
) __n
times.
The code above will eventually call uninitialized_fill_n
, which does the following:
for (; __n > 0; --__n, ++__cur)
std::_Construct(&*__cur, __x);
Here is std::_Contruct
:
template<typename _T1, typename _T2>
inline void
_Construct(_T1* __p, const _T2& __value)
{
// _GLIBCXX_RESOLVE_LIB_DEFECTS
// 402. wrong new expression in [some_]allocator::construct
::new(static_cast<void*>(__p)) _T1(__value);
}
Here you can see it finally calls global operator new
to initialize each element in the vector using the same value.
The conclusion is, using static member to initial data member will work in most of the cases, but it may fail if you plan to use it in STL containers, and the problem is hard to find. I only tried std::vector
, it is quite possible that the problem exists when using other kind of stl containers with MyClass
objects.