[英]char that is outside ASCII range disappearing from concatenated std::string in C++
[英]How are mulitple C++ std::string variables concatenated by GCC?
我對GCC中std::string
串聯的內部實現感興趣。 具體來說,假設我要連接一些相對較大的字符串a
和b
。 一般來說,我非常警惕字符串連接,而字符串在許多高級語言中都是不可變的。
#include <iostream>
int main(){
std::string a = "This would be some kind of data.";
std::string b = "To be concatenated with this, and other things.";
// Is building c this way equivalent to strcpy'ing a, ' ', b, and '\n' into
// a sufficiently large chunk of memory, or are intermediate variables used
// and discarded?
std::string c = a + ' ' + b + '\n';
std::cout << c;
}
正在建立c
這種方式相當於strcpy
“荷蘭國際集團a
, ' '
b
,和'\\n'
成足夠大的組塊的存儲器,或使用並丟棄中間變量?
std::string c = a + ' ' + b + '\\n';
會做:
std::string tmp1 = a.operator+('');
std::string tmp2 = tmp1.operator+(b);
std::string c = tmp2.operator+('\n');
http://www.cplusplus.com/reference/string/string/operator+/
串聯字符串返回一個新構造的字符串對象,其值是lhs后面是rhs的字符串聯。
啟用優化功能后,編譯器將/可能會刪除這些不必要的副本
或手動手動分配字符串。
std::string c;
c.reserve(a.size()+1+b.size()+1);
c += a;
c += ' ';
c += b;
c += '\n';
現在它將不會創建該臨時對象。 即使沒有reserve
。 它不會經常(在大字符串上)重新分配。 因為緩沖區增長了new_size=2*size
(在libstdc ++中)
還值得一提的是C ++ 11可以std::move
內存,請參閱https://stackoverflow.com/a/9620055/362904
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.