[英]Unexpected behavior involving const_cast
我想出了下面的例子,它暴露了一些意想不到的行為。 我希望在 push_back 之后,向量中的任何內容都在那里。 看起來編譯器以某種方式決定重用 str 使用的內存。
有人能解釋一下這個例子中發生了什么嗎? 這是有效的 C++ 代碼嗎?
最初的問題來自負責序列化/反序列化消息的代碼,它使用 const_cast 來刪除常量。 在注意到該代碼的一些意外行為后,我創建了這個簡化的示例,它試圖演示該問題。
#include <vector>
#include <iostream>
#include <string>
using namespace std;
int main()
{
auto str = std::string("XYZ"); // mutable string
const auto& cstr(str); // const ref to it
vector<string> v;
v.push_back(cstr);
cout << v.front() << endl; // XYZ is printed as expected
*const_cast<char*>(&cstr[0])='*'; // this will modify the first element in the VECTOR (is this expected?)
str[1]='#'; //
cout << str << endl; // prints *#Z as expected
cout << cstr << endl; // prints *#Z as expected
cout << v.front() << endl; // Why *YZ is printed, not XYZ and not *#Z ?
return 0;
}
意外行為的發生是由於std::string
的折舊實現中的怪癖。 舊版本的 GCC 使用寫時復制語義實現了std::string
。 這是一個聰明的主意,但它會導致像您看到的那樣的錯誤。 這意味着 GCC 試圖定義std::string
以便只有在修改新的std::string
時才會復制內部字符串緩沖區。 例如:
std::string A = "Hello, world";
std::string B = A; // No copy occurs (yet)
A[3] = '*'; // Copy occurs now because A got modified.
但是,當您使用常量指針時,不會發生復制,因為庫假定不會通過該指針修改字符串:
std::string A = "Hello, world";
std::string B = A;
std::string const& A_ref = A;
const_cast<char&>(A_ref[3]) = '*'; // No copy occurs (your bug)
正如您所注意到的,寫時復制語義往往會導致錯誤。 正因為如此,並且因為復制字符串非常便宜(考慮到所有因素), std::string
copy-on-write實現在 GCC 5 中被貶值和刪除。
那么,如果您使用 GCC 5,為什么會看到此錯誤? 您可能正在編譯和鏈接舊版本的 C++ 標准庫(寫時復制仍然是std::string
的實現)。 這就是導致您出現錯誤的原因。
檢查您正在編譯的 C++ 標准庫版本,如果可能,更新您的編譯器。
std::string
哪種實現?sizeof(std::string) == 32
(編譯 64 位時)sizeof(std::string) == 8
(編譯為 64 位時) 如果您的編譯器使用std::string
的舊實現,則sizeof(std::string)
與sizeof(char*)
相同,因為std::string
實現為指向內存塊的指針。 內存塊是實際包含字符串大小和容量等內容的內存塊。
struct string { //Old data layout
size_t* _data;
size_t size() const {
return *(data - SIZE_OFFSET);
}
size_t capacity() const {
return *(data - CAPACITY_OFFSET);
}
char const* data() const {
return (char const*)_data;
}
};
另一方面,如果您使用的是std::string
的較新實現,則sizeof(std::string)
應該是 32 字節(在 64 位系統上)。 這是因為較新的實現將字符串的大小和容量存儲在std::string
本身中,而不是它指向的數據中:
struct string { // New data layout
char* _data;
size_t _size;
size_t _capacity;
size_t _padding;
// ...
};
新的實施有什么好處? 新的實現有很多好處:
std::string
是 32 字節,我們可以利用小字符串優化。 Small String Optimization 允許長度小於 16 個字符的字符串存儲在_capacity
和_padding
通常占用的空間內。 這避免了堆分配,並且在大多數用例中速度更快。 我們可以在下面看到 GDB 使用std::string
的舊實現,因為sizeof(std::string)
返回 8 個字節:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.