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

标签 c++ string pointers heap-memory invalidation

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

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

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

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

最佳答案

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.

不,这通常不是真的。当您超过容量时,该字符串使用其分配器分配一个完全不同的 block (大小为先前容量的某个因子),并将字符复制过来。除非您保留对字符串实际字符的指针或引用(例如通过 &(*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) 的操作以任何方式影响(显然不包括以下操作表现出未定义的行为,这可能会产生任何影响)。

关于c++ - std::string 重新分配可以使指向堆的指针无效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28707107/

相关文章:

c++ - 使用spdlog(C++)进行记录,记录器未将日志写入文件

python - 如何在Python中查找字符串中所有出现的子字符串

c++ - 复制一个指针,改变拷贝指向的内容而不改变原始指针?

c++ - 为什么我不能对 reference_wrapper<std::chrono::milliseconds> 的 vector 进行排序?

c++ - 在可变参数模板上混合 const 和非常量变量

string - 如何从 golang 中的字符串制作预告片?

c++ - C++ 中的 char 和 char* 有什么区别?

c++ - 作用域 std::unique_ptr 转换

c++ - 在 C++ 中模拟 linux/bash shell?

C++ 用迭代器初始化 vector