std::string 的空間是連續的嗎?
1271044307|%Y-%m-%d|agohover
我知道 std::vector 的空間是連續的,但 std::string 是否如此呢?因為我不知道標準是否有確定此事,所以我最近經常寫如下的 code:
std::string GetDeviceName(cl_device_id id) { size_t len; clGetDeviceInfo(id, CL_DEVICE_NAME, 0, NULL, &len); std::vector<char> buf(len); clGetDeviceInfo(id, CL_DEVICE_NAME, len, &buf[0], NULL); return std::string(&buf[0], len); }
clGetDeviceInfo() 是 OpenCL API 中的一個函式,第一次呼叫會把我需要的資訊長度寫到 len 這個變數中,好讓我配置足夠的記憶體來接受資料。不幸的是因為我不確定 std::string 的空間是否連續,因此我必續另外用 std::vector 來開一個暫存區,再用它來產生 std::string。
能不能省掉這個該死的步驟呢?
好啦,我知道你 google 一下就知道答案了。
- Is std::string’s storage contiguous?
- Cringe not: Vectors are guaranteed to be contiguous
- C++ Standard Library Defect Report: 530. Must elements of a string be contiguous?
所以結論是:
- 標準是沒有很明確地說 std::string 的空間必須連續,但你很難實作出一個符合標準卻又不使用連續空間的 std::string。事實上目前所有的實作都使用連續空間。
- 未來的 C++0x 標準會明確要求 std::string 的儲存空間必須連續。
- 事實上在舊的 C++98 標準中也沒有嚴格規定 std::vector 使用連續的儲存空間,不過發生的問題就如同 std::string 一樣:很難實作出空間不連續卻又符合標準的 std::vector、既存的實作品都使用連續空間、不使用連續空間會讓 client code 用起來很不方便等等。最後到了 C++03 就明確要求 std::vector 須要使用連續儲存空間了。
既然如此,上面的 code 就可以變成這樣了:
std::string GetDeviceName(cl_device_id id) { size_t len; clGetDeviceInfo(id, CL_DEVICE_NAME, 0, NULL, &len); std::string buf(len, 0); clGetDeviceInfo(id, CL_DEVICE_NAME, len, &buf[0], NULL); return buf; }
Comments
page revision: 2, last edited: 12 Apr 2010 03:53
Post preview:
Close preview