gpt4 book ai didi

c++ - "When"编译器是否隐式声明了默认构造函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:19:27 25 4
gpt4 key购买 nike

我知道如果我们不声明它,编译器会生成一个默认构造函数。

“什么时候”是我感到困惑的地方。

答:

class Base {};
int main()
{
return 0;
}

乙:

class Base {};
int main()
{
Base b; // Declare a Base object.
return 0;
}

A和B的区别只是B声明了一个真实的Base对象。在我看来,只有当我们声明一个真实的对象并且编译器没有找到构造函数时,它才会生成一个默认构造函数。

我的问题是:

  1. 代码片段A会生成Base的默认构造函数吗?

  2. 有什么工具可以帮助检查结果吗?我使用 Visual Studio 2010,/d1 reportAllClassLayout 似乎没用。

最佳答案

引用 C++11。

[class.ctor]§5:

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4).

[class.ctor]§6:

A default constructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used (3.2) to create an object of its class type (1.8) or when it is explicitly defaulted after its first declaration.

这意味着它在您的类被定义时被声明,并且在它首次在给定的翻译单元中使用时被定义(作为 inline)。

在您的情况下,这意味着代码片段 A 将包含默认构造函数的声明(但不是定义),而片段 B 将包含两者。

关于c++ - "When"编译器是否隐式声明了默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19347729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com