[英]Where is code of the instantiation of C++ vector?
我有一個非常簡單的代碼如下,它使用 C++ 向量:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> g1;
return 0;
}
通過將代碼復制到網站https://godbolt.org/ ,我知道生成的匯編代碼如下:
main:
stp x29, x30, [sp, -64]!
mov x29, sp
str x19, [sp, 16]
add x0, sp, 40
bl std::vector<int, std::allocator<int> >::vector()** [complete object constructor]
mov w19, 0
add x0, sp, 40
bl std::vector<int, std::allocator<int> >::~vector() [complete object destructor]
mov w0, w19
ldr x19, [sp, 16]
ldp x29, x30, [sp], 64
ret
__static_initialization_and_destruction_0(int, int):
stp x29, x30, [sp, -32]!
mov x29, sp
str w0, [sp, 28]
str w1, [sp, 24]
ldr w0, [sp, 28]
cmp w0, 1
bne .L27
ldr w1, [sp, 24]
mov w0, 65535
cmp w1, w0
bne .L27
adrp x0, _ZStL8__ioinit
add x0, x0, :lo12:_ZStL8__ioinit
bl std::ios_base::Init::Init() [complete object constructor]
adrp x0, __dso_handle
add x2, x0, :lo12:__dso_handle
adrp x0, _ZStL8__ioinit
add x1, x0, :lo12:_ZStL8__ioinit
adrp x0, _ZNSt8ios_base4InitD1Ev
add x0, x0, :lo12:_ZNSt8ios_base4InitD1Ev
bl __cxa_atexit
.L27:
nop
ldp x29, x30, [sp], 32
ret
_GLOBAL__sub_I_main:
stp x29, x30, [sp, -16]!
mov x29, sp
mov w1, 65535
mov w0, 1
bl __static_initialization_and_destruction_0(int, int)
ldp x29, x30, [sp], 16
ret
DW.ref.__gxx_personality_v0:
.xword __gxx_personality_v0
現在我的問題是在哪里可以找到std::vector<int, std::allocator >::vector()的代碼。
如果我在我的代碼中定義一個新的模板類,如下所示:
#include <iostream>
using namespace std;
template <class T, class U> class A {
T x;
U y;
public:
A() { cout << "Constructor Called" << endl; }
};
int main()
{
A<char, char> a;
A<int, double> b;
return 0;
}
我知道 A<char, char> 和 A<int, double> 的代碼是在我自己代碼的目標文件中生成的。 但是對於C++ STL的模板類和模板函數,他們實例化對象的代碼在哪里呢?
C++ 標准庫的庫文件中有,例如libstdc++.so ,但我認為編譯器不會在該 .so 文件中生成代碼。
謝謝!
我知道 A<char, char> 和 A<int, double> 的代碼是在我自己代碼的目標文件中生成的。 但是對於C++ STL的模板類和模板函數,他們實例化對象的代碼在哪里呢?
完全相同:它們是模板類型,只有您的特定實例化才會使std::vector<int, std::allocator >::vector()
存在。
您需要從翻譯單元的角度考慮這一點; 因此,將在包含標頭並實例化該特定類型的每個翻譯單元中找到此機器代碼。
您只是感到困惑,因為 godbolt.org 默認情況下在匯編視圖中不顯示標准庫函數。
單擊“過濾器...”,然后取消選擇“庫函數”。
然后你會得到缺失的符號,例如std::vector<int>
默認構造函數和析構函數。
默認情況下不顯示它們,因為通常對它們不感興趣,並且可能有許多庫函數使輸出混亂。
在某些情況下,標准庫使用.so
的顯式實例化,而不是使用標准庫模板隱式實例化到翻譯單元。 如果我沒記錯的話,Libstdc++ 為std::string
(即std::basic_string<char>
)執行此操作,但我認為沒有任何標准庫實現為std::vector
執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.