回答編集履歴
1
string の構造を推定
test
CHANGED
@@ -59,3 +59,111 @@
|
|
59
59
|
}
|
60
60
|
|
61
61
|
```
|
62
|
+
|
63
|
+
**追記**
|
64
|
+
|
65
|
+
最近の gcc(64ビット) では、sizeof(std::string) は 32 です。
|
66
|
+
|
67
|
+
std::string のソースは見ていませんが、stringオブジェクトのダンプを見て、
|
68
|
+
|
69
|
+
次のように妄想してみました。
|
70
|
+
|
71
|
+
```C++
|
72
|
+
|
73
|
+
#include <iostream>
|
74
|
+
|
75
|
+
#include <string>
|
76
|
+
|
77
|
+
using namespace std;
|
78
|
+
|
79
|
+
|
80
|
+
|
81
|
+
struct String {
|
82
|
+
|
83
|
+
char *data;
|
84
|
+
|
85
|
+
uint64_t size;
|
86
|
+
|
87
|
+
union {
|
88
|
+
|
89
|
+
char here[16];
|
90
|
+
|
91
|
+
uint64_t capacity;
|
92
|
+
|
93
|
+
};
|
94
|
+
|
95
|
+
};
|
96
|
+
|
97
|
+
|
98
|
+
|
99
|
+
void dump(string &s)
|
100
|
+
|
101
|
+
{
|
102
|
+
|
103
|
+
cout << "size() = " << s.size() << ", capacity() = " << s.capacity()
|
104
|
+
|
105
|
+
<< ", s.data() = [" << s.data() << "]\n";
|
106
|
+
|
107
|
+
String *p = reinterpret_cast<String *>(&s);
|
108
|
+
|
109
|
+
|
110
|
+
|
111
|
+
char *data;
|
112
|
+
|
113
|
+
uint64_t capacity;
|
114
|
+
|
115
|
+
if (p->size < 16) data = p->here, capacity = 15;
|
116
|
+
|
117
|
+
else data = p->data, capacity = p->capacity;
|
118
|
+
|
119
|
+
cout << "String: size = " << p->size << ", capacity = " << capacity
|
120
|
+
|
121
|
+
<< ", data = [" << data << "]\n\n";
|
122
|
+
|
123
|
+
}
|
124
|
+
|
125
|
+
|
126
|
+
|
127
|
+
int main()
|
128
|
+
|
129
|
+
{
|
130
|
+
|
131
|
+
string s;
|
132
|
+
|
133
|
+
dump(s);
|
134
|
+
|
135
|
+
s = "abc";
|
136
|
+
|
137
|
+
dump(s);
|
138
|
+
|
139
|
+
s = "abcdefghijklmnopqrstuvwxyz";
|
140
|
+
|
141
|
+
dump(s);
|
142
|
+
|
143
|
+
}
|
144
|
+
|
145
|
+
```
|
146
|
+
|
147
|
+
実行結果
|
148
|
+
|
149
|
+
```
|
150
|
+
|
151
|
+
size() = 0, capacity() = 15, s.data() = []
|
152
|
+
|
153
|
+
String: size = 0, capacity = 15, data = []
|
154
|
+
|
155
|
+
|
156
|
+
|
157
|
+
size() = 3, capacity() = 15, s.data() = [abc]
|
158
|
+
|
159
|
+
String: size = 3, capacity = 15, data = [abc]
|
160
|
+
|
161
|
+
|
162
|
+
|
163
|
+
size() = 26, capacity() = 30, s.data() = [abcdefghijklmnopqrstuvwxyz]
|
164
|
+
|
165
|
+
String: size = 26, capacity = 30, data = [abcdefghijklmnopqrstuvwxyz]
|
166
|
+
|
167
|
+
|
168
|
+
|
169
|
+
```
|