std::string 和 const char *
std::string and const char *
如果我使用
const char * str = "Hello";
运行时
不需要内存allocation/deallocaton
如果我用
const std::string str = "Hello";
是否会在字符串 class 中通过 new/malloc 进行分配?汇编里能找到,但我看不懂
如果答案是 "yes, there will be malloc/new",为什么?如果我需要编辑编辑字符串,为什么只能传递到内部 const char 指针 std::string 并进行实际内存分配?
std::string
的简单实现将需要堆分配,但是如果初始化的字符串在运行时未被修改,则允许编译器优化静态初始化的 std::string
对象,方法是将它们替换为替代实现的对象。
您可以在实例化不可变字符串时使用 const std::string
以确保更好的优化。
will be there an allocation via new/malloc inside string class or not?
视情况而定。 string
对象必须提供一些内存来存储数据,因为那是它的工作。一些实现使用 "small string optimisation",其中对象包含一个小缓冲区,并且仅在字符串太大时才从堆中分配。
Why can there be only pass through to inner const char pointer inside std::string
and do actual memory allocation if I need to edit edit string?
您所描述的不一定是优化(因为每当您修改字符串时都需要额外的运行时检查),并且在任何情况下都不允许迭代器失效规则。
有人提议 string_view
,允许您使用 const string
这样的接口访问现有的字符序列,而无需任何内存管理。它还不是标准的,并且不允许您修改字符串。
C++ 标准实际上并没有说不能只存储指向外部字符串(和长度)的指针。但是,这意味着每次您修改字符串(例如 char& std::string::operator[](size_t index)
)时都必须确保该字符串实际上是可写的。由于大量的字符串使用不会仅使用常量字符串来存储字符串,而是确实会修改字符串[或使用无论如何都不是常量输入的字符串]。
所以,有些问题是;
std::string s = "Hello";
char &c = s[1];
c = 'a'; // Should make string to "Hallo".
如果:
char buffer[1000];
cin.getline(buffer); // Reads "Hello"
std::string s = buffer;
cin.getline(buffer); // Reads "World"
现在 s
的价值是多少?
有很多这样的情况,如果你只是复制原始字符串,它会导致更多问题,而且几乎没有好处。
如果我使用
const char * str = "Hello";
运行时
不需要内存allocation/deallocaton如果我用
const std::string str = "Hello";
是否会在字符串 class 中通过 new/malloc 进行分配?汇编里能找到,但我看不懂
如果答案是 "yes, there will be malloc/new",为什么?如果我需要编辑编辑字符串,为什么只能传递到内部 const char 指针 std::string 并进行实际内存分配?
std::string
的简单实现将需要堆分配,但是如果初始化的字符串在运行时未被修改,则允许编译器优化静态初始化的 std::string
对象,方法是将它们替换为替代实现的对象。
您可以在实例化不可变字符串时使用 const std::string
以确保更好的优化。
will be there an allocation via new/malloc inside string class or not?
视情况而定。 string
对象必须提供一些内存来存储数据,因为那是它的工作。一些实现使用 "small string optimisation",其中对象包含一个小缓冲区,并且仅在字符串太大时才从堆中分配。
Why can there be only pass through to inner const char pointer inside
std::string
and do actual memory allocation if I need to edit edit string?
您所描述的不一定是优化(因为每当您修改字符串时都需要额外的运行时检查),并且在任何情况下都不允许迭代器失效规则。
有人提议 string_view
,允许您使用 const string
这样的接口访问现有的字符序列,而无需任何内存管理。它还不是标准的,并且不允许您修改字符串。
C++ 标准实际上并没有说不能只存储指向外部字符串(和长度)的指针。但是,这意味着每次您修改字符串(例如 char& std::string::operator[](size_t index)
)时都必须确保该字符串实际上是可写的。由于大量的字符串使用不会仅使用常量字符串来存储字符串,而是确实会修改字符串[或使用无论如何都不是常量输入的字符串]。
所以,有些问题是;
std::string s = "Hello";
char &c = s[1];
c = 'a'; // Should make string to "Hallo".
如果:
char buffer[1000];
cin.getline(buffer); // Reads "Hello"
std::string s = buffer;
cin.getline(buffer); // Reads "World"
现在 s
的价值是多少?
有很多这样的情况,如果你只是复制原始字符串,它会导致更多问题,而且几乎没有好处。