Zero Lee的专栏

编译器何时为你产生默认构造函数

总结:
    有四种情况,会导致“编译器必须为未声明构造函数的classes合成一个默认构造函数”。C++ 标准把那些合成物称为隐含的有用默认构造函数。被合成出来的构造函数只能满足编译器(非程序)的需要。它之所以能够完成任务,是借着“调用成员对象或基类的默认构造函数”或是“为每一个对象初始化其虚函数机制或虚基类机制”而完成的。至于没有存在那四种情况而又没有声明构造函数的类,我们说它们拥有的是隐含的无用默认构造函数,实际上它们并不被合成出来。
    在合成的默认构造函数中,只有基类子对象和成员对象会被初始化。所有其它的非静态数据成员,如整数、整数指针、整数数组等等都不会被初始化。这些初始化操作对程序而言有需要,但对编译器而言则没必要。如果程序需要一个“把某指针设为0”的默认构造函数,那么提供它的人应该是程序员。
   
    C++新手一般有两个常见的误解:
1)任何类如果没有定义默认构造函数,编译器就会合成出它来。
2)编译器合成出来的默认构造函数会明确设定“类中每一个数据成员的默认值”。

正如你所见,上述两个没有一个是真的!
-------------------------------------------------------------------------------------------
Summary: 
   There are four characteristics of a class under which the compiler needs to synthesize a default constructor for classes that declare no constructor at all. The Standard refers to these as implicit, nontrivial default constructors. The synthesized constructor fulfills only an implementation need. It does this by invoking member object or base class default constructors or initializing the virtual function or virtual base class mechanism for each object. Classes that do not exhibit these characteristics and that declare no constructor at all are said to have implicit, trivial default constructors. In practice, these trivial default constructors are not synthesized.

Within the synthesized default constructor, only the base class subobjects and member class objects are initialized. All other nonstatic data members, such as integers, pointers to integers, arrays of integers, and so on, are not initialized. These initializations are needs of the program, not of the implementation. If there is a program need for a default constructor, such as initializing a pointer to 0, it is the programmer's responsibility to provide it in the course of the class implementation.

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

As you have seen, neither of these is true.

--------------------------------------------------------------------------------------------

posted on 2007-03-27 10:21 Zero Lee 阅读(1049) 评论(0)  编辑 收藏 引用 所属分类: C++ Performance


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理