2015-12-19 15 views
12

我正在寫一些C++ 11的代碼,使有關的std::string是有效的性質的假設,但代表的行爲是在C +改變+11。在早期的日子裏,的libstdC++的basic_string實施順應了98/03的要求,而不是更嚴格的C++ 11的要求。的libstdC++的版本測試是否使用兼容11-C++的std :: string

據我瞭解,的libstdC++有固定圍繞basic_string問題。問題是人們使用的庫有很多版本,而這些版本並未實現此修補程序。而且我的代碼可能會以許多不愉快的方式默默地失敗。

我想有一個static_assert火災如果用戶試圖編譯我反對的libstdC++那些不符合標準的版本庫。我如何檢測版本,同樣重要的是,我應該尋找哪個版本?

+1

你能說出你的假設嗎? –

+1

我相信即使在C++ 03中也是如此。 COW應該保留這個屬性。 – Puppy

+0

@Puppy:對不起,我說錯了。最好是[看這裏](http://stackoverflow.com/a/29199733/734069)。類似的東西。 –

回答

9

在GCC 5(Runtime Library Section of the changelog)中引入了新的(雙)ABI引入新的符合C++ 11的std::string

_GLIBCXX_USE_CXX11_ABI決定是否使用舊的或新的ABI,所以只檢查:

#if _GLIBCXX_USE_CXX11_ABI 

當然,這是特定於只的libstdC++中。

5
#include <string> 

static_assert(sizeof(std::string) != sizeof(void*), "using ref-counted string"); 

int 
main() 
{ 
} 

演示:http://melpon.org/wandbox/permlink/P8LB79Cy6ASZlKuV

這個測試利用所有已知的std ::的std::string lib中實現的內部工作,特別是海灣合作委員會的執行。

gcc的引用計數string由一個單一指針,以保持該尺寸,容量,引用計數,和數據串的一個動態分配的結構。 Scott Meyers對有效STL中的字符串實現做了很好的總結,在2001年的時間框架中是準確的。我相信(我可能會誤解)該書第15項中的「實現C」是gcc的std :: string。

對於短字符串實現(幾乎由C++ 11強制執行),string不能再由堆棧上的單個指針組成。 Scott的實現D是我們第一次看到那個時代的短串實現。這是VS/Dinkumware string。該sizeof(string)本身會包含一些數據緩存來保存,沒有分配字符串數據。

人們可以在什麼不同的實現方式與該短程序做得到一個處理:

#include <iostream> 
#include <string> 

int 
main() 
{ 
    std::string s; 
    std::cout << "word size is   " << sizeof(void*)/sizeof(char) << '\n'; 
    std::cout << "sizeof string is  " << sizeof(s) << '\n'; 
    std::cout << "short string buffer is " << s.capacity() << '\n'; 
} 

此打印出字的大小,通常爲4或8(32位/ 64位)的至少一個實施(libC++)在這個硬件特性上改變了它的特性。然後打印出sizeof(string),它將是字長的倍數,然後輸出string的空行,這將是短字符串緩衝區的大小(如果存在)。

這是一個有些不完整的調查顯示:

gcc/libstdc++ 4.8 

word size is   8 
sizeof string is  8 
short string buffer is 0 

gcc/libstdc++ 5.2 

word size is   8 
sizeof string is  32 
short string buffer is 15 

clang/libc++ -arch i386 OS X 

word size is   4 
sizeof string is  12 
short string buffer is 10 

clang/libc++ -arch x86_64 OS X 

word size is   8 
sizeof string is  24 
short string buffer is 22 

VS-2015 

word size is   4 
sizeof string is  24 
short string buffer is 15 

在本調查中,只有gcc/libstdC++ 4.8顯然不使用短字符串優化。而只有gcc/libstdC++ 4.8有sizeof(string) == 1 word。這實際上是本次調查中使用引用計數的唯一實現。

總而言之,對libstdC++的std::string這個測試是不可移植的。但通過規範它不一定是。我們可以利用這一領域已知的海灣合作委員會發展歷史。 spec(問題)說它只需要在gcc的libstdC++上工作。

+0

你能簡單地解釋一下爲什麼會這樣做? COW字符串只有一個'void *'(私有)數據成員,當然沒有虛函數? – vsoftco

+1

好的,完成了....... –

+0

謝謝,很好的解釋。 – vsoftco

相關問題