开发者

Consequences of caching string length in a native C++ class?

So we have a custom string class that just wraps a basic C string: char* or a wchar_t*. The o开发者_C百科nly data member of our custom string class is this pointer. Anyways, here at work we are debating adding another member that caches the length of the internal char array. So instead of

MyString::Count { return _tcslen(foo); }

we could just write:

MyString::Count { return m_count; }

But I'm sure there is a special gotcha that would bite us if we did that. You know, some special way to break such an implementation wide open. So my question is, what are the downsides of caching the length?


First thing: don't do it unless you have profiling data showing this is really a bottleneck. If you don't have that, you've all been wasting your time arguing about this IMO. Make your code correct first, then attack the important bottlenecks.

If you do cache it, make sure all the paths that could modify the internal string also update the m_count appropriately.

If your wrapper hands out a non-const reference or a pointer to the data, don't cache it - you can't be certain that the value will remain fixed.


There are no real downsides to caching the length. The std::string class does the same thing. This also allows you to store NUL characters within your data if you choose to.

Just make sure your data and the cached value are always in sync through accessors and possibly protected data members.


What if someone changes the string contents without calling a special "update count" function? At that point, your saved count and the string itself are out of sync, which could lead to all sorts of problems, including crashes.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜