1. 代码
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
namespace chen101 {
class Test {
private:
int value;
public:
Test()
: value(99) {
cout << this << " : Test()" << endl;
}
~Test() {
cout << this << " : ~Test()" << endl;
}
};
}
namespace testAuto {
using namespace::chen101;
void test() {
Test test1 = Test();
auto test2 = Test();
string str1 = "1";
auto str2 = str1;
string str3 = str1;
cout << 1 << endl;
}
}
int main() {
testAuto::test();
return 0;
}
2. 反汇编
Test test1 = Test();
00275D1A lea ecx,[test1]
00275D1D call chen101::Test::Test (02713DEh)
00275D22 mov dword ptr [ebp-4],0
auto test2 = Test();
00275D29 lea ecx,[test2]
00275D2C call chen101::Test::Test (02713DEh)
00275D31 mov byte ptr [ebp-4],1
string str1 = "1";
00275D35 push offset string "1" (027DE04h)
00275D3A lea ecx,[str1]
00275D3D call std::basic_string<char,std::char_traits<char>,std::allocator<char> >::basic_string<char,std::char_traits<char>,std::allocator<char> > (027111Dh)
00275D42 mov byte ptr [ebp-4],2
auto str2 = str1;
00275D46 lea eax,[str1]
00275D49 push eax
00275D4A lea ecx,[str2]
00275D4D call std::basic_string<char,std::char_traits<char>,std::allocator<char> >::basic_string<char,std::char_traits<char>,std::allocator<char> > (0271398h)
00275D52 mov byte ptr [ebp-4],3
string str3 = str1;
00275D56 lea eax,[str1]
00275D59 push eax
00275D5A lea ecx,[str3]
00275D60 call std::basic_string<char,std::char_traits<char>,std::allocator<char> >::basic_string<char,std::char_traits<char>,std::allocator<char> > (0271398h)
00275D65 mov byte ptr [ebp-4],4
- 来个有颜色的标记
- 可以看出:
用显示定义比如
string str2 = str1
还是auto str3 = str1
或者自定义的类,对应的汇编是一样的,也就是调用的过程是一样的,不会消耗额外的时间。
我自己认为,额外的消耗时间应该是在编译的时候,编译器要寻找
auto
对应的是哪一种具体的类型。
-
自定义的类的构造和析构函数的输出:
-
来个去掉符号名的汇编,这样看得清晰一点