什么是合成构造函数?

4
什么是合成构造函数?我大致了解,合成构造函数是由编译器隐式创建的构造函数,还会初始化其成员类对象,但它可能会或可能不会满足程序实现的需求。这个定义正确吗?
在什么情况下会合成构造函数?在什么情况下不会?

https://dev59.com/oHI-5IYBdhLWcg3whYwr - Martin York
1个回答

4
以下文章比我能够做到的更好地回答了你的问题。我引用了一段简短的摘录,让你了解它的风格。在引语下方有一个链接。
顺便提一句,我引用的“C++参考指南”声称其中有529页营养丰富的C++信息;你可能想要将其加入书签。

A constructor initializes an object. A default constructor is one that can be invoked without any arguments. If there is no user-declared constructor for a class, and if the class doesn't contain const or reference data members, C++ implicitly declares a default constructor for it.

Such an implicitly declared default constructor performs the initialization operations needed to create an object of this type. Note, however, that these operations don't involve initialization of user-declared data members.

For example:

class C
{
    private:
        int n;
        char *p;
    public:
        virtual ~C() {}
};

void f()
{
    C obj; // 1 implicitly-defined constructor is invoked
}

C++ synthesized a constructor for class C because it contains a virtual member function. Upon construction, C++ initializes a hidden data member called the virtual pointer, which every polymorphic class has. This pointer holds the address of a dispatch table that contains all the virtual member functions' addresses for that class.

The synthesized constructor doesn't initialize the data members n and p, nor does it allocate memory for the data pointed to by the latter. These data members have an indeterminate value once obj has been constructed. This is because the synthesized default constructor performs only the initialization operations that are required by the implementation—not the programmer—to construct an object.

http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=15


1
那么,在这里,“合成”的含义是什么?构造函数与什么合成?我想知道“合成”一词在构造函数上下文中的解释。 - Amumu
1
@Anumu:合成构造函数是你没有编写的构造函数。在C#中,我们称之为“默认”构造函数。 - Robert Harvey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接