强制编译器在C++中提供默认构造函数

Utt*_*kar 2 c++ constructor

我编写了一个C++程序而没有定义任何构造函数.以下是代码:

#include<iostream>
using namespace std;
class test
{
    public:

        void print()
        {
            cout<< "Inside Print"<<endl;
        }
};
int main()
{
   test t;
   t.print();
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我解组代码时,我没有发现任何调用默认构造函数的情况.以下是主要功能的汇编代码片段:

8 main:
      9 .LFB1516:
     10         pushl   %ebp
     11 .LCFI0:
     12         movl    %esp, %ebp
     13 .LCFI1:
     14         subl    $8, %esp
     15 .LCFI2:
     16         andl    $-16, %esp
     17         movl    $0, %eax
     18         subl    %eax, %esp
     19         leal    -1(%ebp), %eax
     20         movl    %eax, (%esp)
     21         call    _ZN4test5printEv
     22         movl    $0, %eax
     23         leave
     24         ret
Run Code Online (Sandbox Code Playgroud)

如您所见,call上面的代码段中只有一条指令(第21行).它正在调用该print()函数.现在我稍微修改了我的代码并引入了一个constructor.以下是代码:

#include<iostream>
using namespace std;
class test
{
    public:
        test()
        {
        }
        void print()
        {
            cout<< "Inside Print"<<endl;
        }
};
int main()
{
    test t;
    t.print();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我再次拆解代码,发现以下内容:

 8 main:
      9 .LFB1519:
     10         pushl   %ebp
     11 .LCFI0:
     12         movl    %esp, %ebp
     13 .LCFI1:
     14         subl    $8, %esp
     15 .LCFI2:
     16         andl    $-16, %esp
     17         movl    $0, %eax
     18         subl    %eax, %esp
     19         leal    -1(%ebp), %eax
     20         movl    %eax, (%esp)
     21         call    _ZN4testC1Ev
     22         leal    -1(%ebp), %eax
     23         movl    %eax, (%esp)
     24         call    _ZN4test5printEv
     25         movl    $0, %eax
     26         leave
     27         ret
Run Code Online (Sandbox Code Playgroud)

如您所见,它在第21行调用了构造函数.现在我的问题是,如果我没有在我的代码中定义任何构造函数,编译器是否在所有情况下都提供默认构造函数?如果没有,那么在什么情况下,或者我怎样才能强制编译器为我提供默认构造函数?

抱歉这个冗长的问题:P

Ker*_* SB 13

该程序的行为应该如此.机器代码生成不是标准的一部分,您无权期望任何特定的机器代码输出 - 您只能保证输出程序完成您告诉它的操作.

  • 例如,`static_cast <volatile void>(0);`是一个有效的表达式,可能不会创建任何机器代码; 但它是一个非常明智的C++语句. (2认同)

Nem*_*ric 6

为什么要强制你的编译器膨胀你的二进制文件并减慢你的程序?

只有在有意义的情况下,好的编译器才会调用默认构造函数(或任何其他函数) - 如果调用它会产生任何影响.

优化只会从程序中排除默认构造函数(它什么都不做).