是否为 C++ 中的默认构造函数创建了汇编代码?
如果我没有在 C++ 的类中定义默认构造函数或任何其他构造函数,我已经读到编译器会为您创建默认构造函数。但我创建了一个测试类,将其编译为汇编代码并检查发现没有创建任何此类内容。
有人可以澄清默认构造函数的代码是如何创建的,或者是否首先创建的?
If I do not define a default constructor in a class in C++ , or any other constructors, I have read that the compiler creates a default constructor for you. But I created a test class, compiled it to assembly code and checked to find that nothing of the sort is created.
Can someone clarify how the code for default constructor is created, or if it is created in the first place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您需要,则会创建默认构造函数,例如:
12.1:
此外,如果您的类不需要在构造函数中执行任何操作,则编译器可能会选择不生成代码,即使按照标准构造函数应该存在。
Default constructor is created if you need it, e.g:
12.1:
Also, if your class doesn't require anything to be done in the constructor, a compiler may choose to not generate the code, even though by the standard the constructor should exist.
C++ != 汇编。
汇编是已编译的 C++ 程序的(一种可能的)输出,该程序可能包含也可能不包含某些优化,这些优化可能会省略对可能为空的构造函数的调用。
换句话说,该语言说有一个默认构造函数,但它只描述行为,而不描述实现。如果一个实现感觉不需要生成代码,那么它就不需要生成代码。
C++ != Assembly.
Assembly is (one possible) output for a compiled C++ program, which may or may not have included certain optimizations which could have elided the call to a possibly empty constructor.
In other words, the language says there's a default constructor all right, but it only describes behavior, not implementation. If an implementation feels like it doesn't need to generate code, it doesn't have to.
C++03 标准的规定如下:
§12.1/5:
§12.1/6:
§12.1/7:
这意味着对于具有隐式声明但未隐式定义默认构造函数的类,或对于具有隐式定义的类>简单的默认构造函数,可能不需要生成代码。
Here's what the C++03 standard says:
§12.1/5:
§12.1/6:
§12.1/7:
The implication is that for classes with implicitly declared but not implicitly defined default constructors, or for classes with implicitly defined trivial default constructors, no code generation may be necessary.
您是否想问您的编译器是否确实为默认构造函数发出代码?
这取决于优化。大多数现代编译器在与 -O0 一起使用时会发出默认的构造函数代码序列,但如果未使用它并且您使用 -O2 或更高版本,则会对其进行优化。
Did you want to ask if your compiler actually emits code for a default constructor?
That depends on the optimization. Most modern compilers will emit the default constructor code sequence when used with -O0, but will optimize it away if it is unused and you use -O2 or higher.