following on discussion question, wondering how 1 using native c++ determine programmatically whether or not std::string implementation using utilizes copy-on-write (cow)
i have following function:
#include <iostream> #include <string> bool stdstring_supports_cow() { //make sure string longer size of potential //implementation of small-string. std::string s1 = "012345678901234567890123456789" "012345678901234567890123456789" "012345678901234567890123456789" "012345678901234567890123456789" "012345678901234567890123456789"; std::string s2 = s1; std::string s3 = s2; bool result1 = (&s1[0]) == (&s2[0]); bool result2 = (&s1[0]) == (&s3[0]); s2[0] = 'x'; bool result3 = (&s1[0]) != (&s2[0]); bool result4 = (&s1[0]) == (&s3[0]); s3[0] = 'x'; bool result5 = (&s1[0]) != (&s3[0]); return result1 && result2 && result3 && result4 && result5; } int main() { if (stdstring_supports_cow()) std::cout << "std::string cow." << std::endl; else std::cout << "std::string not cow." << std::endl; return 0; }
the problem can't seem find c++ tool chain returns true. there flaw in assumption how cow implemented std::string?
update: based on kotlinski comments, i've changed use of writeble references data() in function, seems return "true" implementations.
bool stdstring_supports_cow() { //make sure string longer size of potential //implementation of small-string. std::string s1 = "012345678901234567890123456789" "012345678901234567890123456789" "012345678901234567890123456789" "012345678901234567890123456789" "012345678901234567890123456789"; std::string s2 = s1; std::string s3 = s2; bool result1 = s1.data() == s2.data(); bool result2 = s1.data() == s3.data(); s2[0] = 'x'; bool result3 = s1.data() != s2.data(); bool result4 = s1.data() == s3.data(); s3[0] = 'x'; bool result5 = s1.data() != s3.data(); return result1 && result2 && result3 && result4 && result5; }
note: according n2668: "concurrency modifications basic string", in upcoming c++0x standard, cow option removed basic_string. james , beldaz bringing up.
using &s1[0]
take adress not want, [0]
returns writable reference , create copy.
use data() instead, returns const char*, , tests may pass.
Comments
Post a Comment