c++ - C++中的字符串管理

标签 c++ string

在使用 Java 一段时间后,我决定回到 C++,现在我对字符串在 C++ 中的工作方式感到很困惑。

首先,假设我们有一个函数:

void fun() {
   int a = 1;
   Point b(1,2);
   char c[] = "c-string";
}

据我了解,ab 分配在堆栈上。 c(指针)也在堆栈上分配,但内容(“c-string”)愉快地生活在堆上。

Q1: c 的内容是否会在函数 fun 结束时自动释放?

其次,假设我们有一个 C++ string:

void fun2() {
  (1) string s = "c++ string";
  (2) s += "append";
  (3) s = "new contents";
  (4) s = "a" + s + "c";
}

String documentation对字符串的工作方式不太具体,所以这里有问题:

Q2s的内容是否在fun2结束后自动释放?

问题 3:当我们连接两个字符串时会发生什么?我应该关心内存使用情况吗? (第 2 行)

问题 4: 当我们覆盖字符串的内容时会发生什么(第 3 行)- 内存如何,我应该担心吗?原来分配的空间是否被重新利用?

问题 5: 如果我构造一个像这样的字符串(第 4 行)会怎样?这个很贵吗?字符串文字("a""c")是合并(如在 Java 中)还是在整个最终可执行文件中重复?

我最终想学习的是如何在 C++ 中正确使用字符串。

感谢阅读本文,
魁魁格

最佳答案

As I understand, a and b are allocated on the stack. c (the pointer) is allocated on the stack too, but the contents ("c-string") live happily on the heap.

错了,它们都存在于自动内存(堆栈)中。甚至 char 数组。在 C++ 中,字符串是 std::string 类型的对象。

Q1: Are the contents of c automatically deallocated when the function fun ends?

是的。

Q2: Are the contents of s automatically deallocated after fun2 ends?

是的。

Q3: What does happen when we concatenate two strings? Should I care about memory usage? (line 2)

它们是串联的,内存是自动管理的。 (假设我们谈论的是 std::string 而不是 char[]char*

Q4: What happens when we overwrite the contents of a string (line 3) - what about memory, should I worry? Is the originally allocated space reused?

实现细节。它可以重复使用,如果以前的内存不能容纳新的内容,它可以重新分配。

Q5: What if I construct a string like this (line 4). Is it expensive? Are string literals ("a","c") pooled (like in Java) or repeated throughout the final executable?

字符串文字可以合并,但这不是必需的。对于大型串联,通常使用 std::stringstream 代替(类似于 Java)。但首先要分析,不要过早地进行优化。但这并不是说它们都不是字符串文字。

char* pStr = "this is a string literal";

这驻留在只读内存中,无法修改。

What I am ultimately trying to learn is how to correctly use strings in C++.

使用 std::string

关于c++ - C++中的字符串管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12257815/

相关文章:

C++ - 为什么我在执行期间收到 SIGTRAP?

C++ 循环依赖与邻接表表示的混淆

c++ - Android NDK 中有异步文件 I/O 吗?

c - 字符串、字符数组大小和 calloc --- 是什么导致了这个段错误?

python - 相当于 python 在 bash 中的 textwrap dedent

c# - 如何从字符串中分离数据

c++ - 了解 MergeSort C++ 的部分递归实现

ios - 空字符串使 Swift 有条件地崩溃

java - 获取单词在字符串数组中的位置

c++ - 类型转换 std::placeholder