std::string 重新分配可以使指向堆的指针无效吗?

Can std::string reallocation invalidate pointer to heap?

我的问题是关于以下场景:

std::string *ps = new std::string();
*ps = aVeryLargeString;

根据我的经验,通常发生的情况是 aVeryLargeString 超出了 *ps 的容量,因此 *ps 分配了额外的内存,保持起始位置不变。 因此 ps 仍将指向新字符串,因为内存中的位置是相同的。

但是,如果该内存位置没有足够的连续 space 会怎样?重新分配是否将字符串移动到完全不同的位置,从而使指针无效?

What usually happens from my experience is that aVeryLargeString exceeds the capacity of *ps, so *ps allocates extra memory, keeping the starting position the same.

不,这通常不是真的。当您超过容量时,该字符串使用其分配器分配一个完全不同的块(大小为先前容量的某个因子),并将字符复制过来。除非您保留指向字符串实际字符的指针或引用(例如通过 &(*ps)[0]ps->c_str()),而不是指向字符串对象本身的指针(即 ps是),你不用担心这个。

So ps will still point to the new string as the location in memory is the same.

ps 不会,也不可能受到对其指向的字符串 (*ps) 的操作的任何影响( 显然不包括表现出未定义行为的操作, 这可能会产生任何影响).