开发者

Does the imlementation of std::string, I use, implement ref-counting or not?

开发者 https://www.devze.com 2023-02-18 12:37 出处:网络
I develop for iOS and use XCode 3.2.5, GCC 4.2. UPD This code works: string s = \"aaaa\"; string s1 = 开发者_如何学JAVAs;

I develop for iOS and use XCode 3.2.5, GCC 4.2.

UPD

This code works:

string s = "aaaa";
string s1 = 开发者_如何学JAVAs;

assert(s.data() == s1.data());

Does it mean ref-counting is used? Or '==' is overloaded for const char* somehow to compare contents, not addresses?

UPD

Okay, it does.


There are different ways of finding out, the first of which is plainly looking at the code. std::string is a typedef to an instantiation of the basic_string template, and being a template, all the code is available to you in the headers. Note that reading standard library headers can be both enlightening and hard. And yet, you don't even need to understand the code, you might get some good hints from a cursory look (as by the fact that basic_string contains a member _M_p with a _M_refcount sub member)

If you don't want to read the code, you can approach the problem from a practical point of view and measure the effects that a copy-on-write implementation would have. You can, for example create a long string [*], then copy it to a different string and compare the addresses of the data() that stores the actual contents.

[*] The reason for the long string is to avoid getting confused with some other implementations, as small object implementation that could be used by the compiler and by which a string could contain a small buffer to avoid dynamic memory allocations for very small uses.


An easy way to find out would be to copy-construct or assign a string, and compare the results of their data() method - if their data area is at the same location in memory, they must be using some form of reference counting.


One obvious answer is: it's unspecified. As far as I know, it's not only unspecified in the standard, but in every implementation. But for what it's worth, g++ uses a reference counted implementation, at least through the latest version I've looked at (4.4.2).


ref counting is really useful, copy on write...etc. a lot of code relies on it to be efficient. it's probably a bad idea to abandon it. better to have a function that explicitly obtains a copy of a string the way MS does it (lock buffer, etc.) if you're going to tinker with internals in an unsafe manner.

0

精彩评论

暂无评论...
验证码 换一张
取 消