/********************************************\
| 欢迎转载, 但请保留作者姓名和原文链接, 祝您进步并共勉! |
\********************************************/
Chapter 2. The Semantics of Constructors
----------------------------------------
2.1 Default Constructor Construction
作者: Jerry Cat
时间: 2006/04/27
链接: http://www.cppblog.com/jerysun0818/archive/2006/04/28/6407.html
========================================
Global objects are guaranteed to have their associated memory "zeroed out" at program start-up. Local objects allocated on the program stack and heap objects allocated on the free-store do not have their associated memory zeroed out; rather, the memory retains the arbitrary bit pattern of its previous use.
If there is no user-declared constructor for class X, a default constructor is implicitly declared…. A constructor is trivial(琐碎, 微不足道, 啥也不干) if it is an implicitly declared default constructor….
1). Member Class Object with Default Constructor:
If a class without any constructors contains a member object of a class with a default constructor, the implicit default constructor of the class is nontrivial and the compiler needs to synthesize a default constructor for the containing class. This synthesis, however, takes place only if the constructor actually needs to be invoked.
An interesting question, then: Given the separate compilation model of C++, how does the compiler prevent synthesizing multiple default constructors, for example, one for file A.C and a second for file B.C? In practice, this is solved by having the synthesized default constructor, copy constructor, destructor, and/or assignment copy operator defined as inline. An inline function has static linkage and is therefore not visible outside the file within which it is synthesized. If the function is too complex to be inlined by the implementation, an explicit non-inline static instance is synthesized.
For example, in the following code fragment, the compiler synthesizes a default constructor for class Bar:
class Foo { public: Foo(), Foo( int ) ... };
class Bar { public: Foo foo; char *str; };
void foo_bar() {
Bar bar; // Bar::foo must be initialized here
if ( str ) { } ...
}
The synthesized default constructor contains the code necessary to invoke the class Foo default constructor on the member object Bar::foo, but it does not generate any code to initialize Bar::str. Initialization of Bar::foo is the compiler's responsibility; initialization of Bar::str is the programmer's. The synthesized default constructor might look as follows:
____To simplify our discussion, these examples ignore the insertion of the implicit this pointer.
// possible synthesis of Bar default constructor
// invoke Foo default constructor for member foo
inline Bar::Bar()
{
foo.Foo::Foo(); // Pseudo C++ Code
}
Again, note that the synthesized default constructor meets only the needs of the implementation, not the needs of the program.
What happens if there are multiple class member objects requiring constructor initialization? The language requires that the constructors be invoked in the order of member declaration within the class. This is accomplished by the compiler. It inserts code within each constructor, invoking the associated default constructors for each member in the order of member declaration. This code is inserted just prior to the explicitly supplied user code. For example, say we have the following three classes:
class Dopey { public: Dopey(); ... };
class Sneezy { public: Sneezy( int ); Sneezy(); ... };
class Bashful { public: Bashful() ... };
and a containing class Snow_White:
class Snow_White {
public:
Dopey dopey;
Sneezy sneezy;
Bashful bashful;
// ...
private:
int mumble;
};
If Snow_White does not define a default constructor, a nontrivial default constructor is synthesized that invokes the three default constructors of Dopey, Sneezy, and Bashful in that order. If, on the other hand, Snow_White defines the following default constructor:
// programmer coded default constructor
Snow_White::Snow_White() : sneezy( 1024 )
{
mumble = 2048;
}
it is augmented as follows:
// Compiler augmented default constructor
// Pseudo C++ Code
Snow_White::Snow_White()
{
// insertion of member class object constructor invocations
dopey.Dopey::Dopey();
sneezy.Sneezy::Sneezy( 1024 );
bashful.Bashful::Bashful();
// explicit user code
mumble = 2048;
}
2). Base Class with Default Constructor:
Similarly, if a class without any constructors is derived from a base class containing a default constructor, the default constructor for the derived class is considered nontrivial and so needs to be synthesized. The synthesized default constructor of the derived class invokes the default constructor of each of its immediate base classes in the order of their declaration. To a subsequently derived class, the synthesized constructor appears no different than that of an explicitly provided default constructor.
What if the designer provides multiple constructors but no default constructor? The compiler augments each constructor with the code necessary to invoke all required default constructors. However, it does not synthesize a default constructor because of the presence of the other user-supplied constructors. If member class objects with default constructors are also present, these default constructors are also invoked梐fter the invocation of all base class constructors.
3). Class with a Virtual Function:
There are two additional cases in which a synthesized default constructor is needed:
(1). The class either declares (or inherits) a virtual function
(2). The class is derived from an inheritance chain in which one or more base classes are virtual
In both cases, in the absence of any declared constructors, implementation bookkeeping necessitates the synthesis of a default constructor. For example, given the following code fragment:
class Widget {
public:
virtual void flip() = 0;
// ...
};
void flip( const Widget& widget ) { widget.flip(); }
// presuming Bell and Whistle are derived from Widget
void foo() {
Bell b; Whistle w;
flip( b );
flip( w );
}
the following two class "augmentations" occur during compilation:
(3). A virtual function table (referred to as the class vtbl in the original cfront implementation) is generated and populated with the addresses of the active virtual functions for that class.
(4). Within each class object, an additional pointer member (the vptr) is synthesized to hold the address of the associated class vtbl.
In addition, the virtual invocation of widget.flip() is rewritten to make use of widget's vptr and flip()'s entry into the associated vtbl:
// simplified transformation of virtual invocation:
widget.flip()
( * widget.vptr[ 1 ] ) ( &widget )
where:
____1 represents flip()'s fixed index into the virtual table, and
____&widget represents the this pointer to be passed to the particular invocation of flip().
For this mechanism to work, the compiler must initialize the vptr of each Widget object (or the object of a class derived from Widget) with the address of the appropriate virtual table. For each constructor the class defines, the compiler inserts code that does just that (this is illustrated in Section 5.2). In classes that do not declare any constructors, the compiler synthesizes a default constructor in order to correctly initialize the vptr of each class object.
4). Class with a Virtual Base Class:
Virtual base class implementations vary widely across compilers. However, what is common to each implementation is the need to make the virtual base class location within each derived class object available at runtime. For example, in the following program fragment:
class X { public: int i; };
class A : public virtual X { public: int j; };
class B : public virtual X { public: double d; };
class C : public A, public B { public: int k; };
// cannot resolve location of pa->X::i at compile-time
void foo( const A* pa ) { pa->i = 1024; }
main() {
foo( new A );
foo( new C );
// ...
}
the compiler cannot fix the physical offset of X::i accessed through pa within foo(), since the actual type of pa can vary with each of foo()'s invocations. Rather, the compiler must transform the code doing the access so that the resolution of X::i can be delayed until runtime. In the original cfront implementation, for example, this is accomplished by inserting a pointer to each of the virtual base classes within the derived class object. All reference and pointer access of a virtual base class is achieved through the associated pointer. In our example, foo() might be rewritten as follows under this implementation strategy:
// possible compiler transformation
void foo( const A* pa ) { pa->__vbcX->i = 1024; }
where __vbcX represents the compiler-generated pointer to the virtual base class X.
As you've no doubt guessed by now, the initialization of __vbcX (or whatever implementation mechanism is used) is accomplished during the construction of the class object. For each constructor the class defines, the compiler inserts code that permits runtime access of each virtual base class. In classes that do not declare any constructors, the compiler needs to synthesize a default constructor.
2.1 小结:
=-=-=-=-=
Programmers new to C++ often have two
common misunderstandings:
1. That a default constructor is synthesized for every class that does not define one
2. That the compiler-synthesized default constructor provides explicit default initializers for each data member declared within the class
posted on 2006-04-28 03:00
Jerry Cat 阅读(1035)
评论(3) 编辑 收藏 引用