c++ - 在 STL 中使用引用计数的数据结构有哪些行为异常?

标签 c++ data-structures stl garbage-collection containers

Scott Meyer 在“Effective STL”中说,在决定使用哪种数据结构时要考虑的事情之一是容器是否使用引用计数。他说这种方法存在一些行为异常。

其中有哪些?为什么像“string”和“rope”这样的容器会出现异常行为?

最佳答案

正如其他人所说,典型的例子是std::string。除了多线程程序中锁定的性能问题外,引用计数字符串还存在无线程问题。想象一下:

string s = "hello";
string t = s;                   // s and t share data
char &c = t[0];                 // copy made here, since t is non-const

问题是非常量 operator[] 必须复制字符串(如果它是共享的),因为返回的引用稍后可以用来修改字符串(您可以将其分配给非引用 char,但 operator[] 不知道它的行为应该有任何不同)。另一方面,const operator[] 应该避免复制,因为那会消除引用计数的所有好处(这意味着你总是 在练习中复制)。

const char &get_first(const string &s) {
    return s[0];                // no copy, s is const
}

string s = "hello";
string t = s;                   // s and t share data
const char &c1 = get_first(t);  // no copy made here
const char &c2 = t[0];          // copy made, since t is non-const
// c1 just got invalidated (in fact, it's pointing at s[0], not t[0]).
s[0] = 'X';
printf("%c, %c\n", c1, c2);     // outputs "X, h"

如您所见,这种区别令人困惑,可能会导致真正意外的行为。

这是一篇关于写时复制语义及其对性能影响的旧文章:http://www.gotw.ca/gotw/045.htm .

这里是提议将 std::string 更改为在 C++11 标准中不被引用计数:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2534.html .这就是上面例子的基础。

关于c++ - 在 STL 中使用引用计数的数据结构有哪些行为异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12197609/

相关文章:

c++ - 防止定义某些模板

c++ - fps游戏中的瞄准机器人如何工作?

c++ - 为什么 pA、pB、pC 不相等?

c++ - 如何获取列表中的倒数第二个元素?

c++ - 如何对两个 vector 进行运算并将结果保存到另一个 vector

C++ 标准库可移植性

c++ - cout 能抛出异常吗?

java - 从 ConcurrentLinkedDeque 的特定位置获取元素

algorithm - 如何找到有向无环图的根

arrays - 删除排序数组中最小值的时间复杂度