问题
This question relates to this one.
As I mentioned in previous question I've decided to inherit my class from Win structure BITMAP to provide some extended functionality.
I've noticed interest detail in compiled program behavior. First I have defined default constructor for my class like below:
CPreviewFrame::CPreviewFrame():
m_bufferSize( 0 )
{
bmBits = NULL; //ensure that compiler in debug won't init it with 0xccccc... and delete[] will do the job
}
In idea compiler had to generate code which calls default constructor for base type even if it wasn't called manually in init list. But while debugging I noticed that BITMAP's data members are not initialized! I added manual initialize for BITMAP and it worked - all data members were initialized by zeros:
CPreviewFrame::CPreviewFrame():
BITMAP( ),
m_bufferSize( 0 )
{
//bmBits = NULL; //it's not needed anymore probably
}
Why does it happen? Isn't compiler obligated to call default constructor or it's applied to classes only? (it can't be so I think - only difference is in default access qualifiers for members and for inheritance)
回答1:
If you do not provide an explicit initializer for a POD-struct, then the object has an indeterminate initial value per Section 8.5/9 of the C++ standard. Adding an initializer for BITMAP
that is an empty set of parenthesis to the initializer list of your CPreviewFrame
constructor value-initializes the BITMAP
object per Section 8.5/7. According to Section 8.5/5, that will mean all the non-static members of BITMAP
will be zero-initialized since they are not arrays, unions, or class-types.
In your initial example though, you only initialized the bmBits
member of the BITMAP
structure in the actual body of the CPreviewFrame
constructor ... that leaves the rest of the data-members of BITMAP
with values that are indeterminate since no initializer was specified for the BITMAP
structure itself. Since each non-static data-member of a class is initialized before the actual body of the constructor is called, the lack of an explicit initializer for BITMAP
, which is a non-static POD-struct data-member of your CPreviewFrame
class, means that the behavior described in 8.5/9, where the values are set to an indeterminate initial value, takes effect.
来源:https://stackoverflow.com/questions/7556636/strange-behavior-of-default-constructor-in-a-class-inherited-from-pod-struct