gpt4 book ai didi

c++ - (c/c++) 字符串文字的拷贝是否在 TEXT 部分共享内存?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:04:33 25 4
gpt4 key购买 nike

如果我调用一个函数myObj.setType("流体");在一个程序中多次,内存中保存了多少份文字“流体”?编译器能否识别出该字面量已经定义并再次引用它?

最佳答案

这与 C++(语言)无关。相反,它是编译器可以进行的“优化”。因此,答案是,具体取决于您使用的编译器/平台。

@David 这是来自 latest draft of the language :

§ 2.14.6 (page 28)

Whether all string literals are distinct (that is, are stored in non overlapping objects) is implementation defined. The effect of attempting to modify a string literal is undefined.

重点是我的。

换句话说,C++ 中的字符串文字是不可变的,因为修改字符串文字是未定义的行为。因此,编译器是免费的,以消除冗余拷贝。

顺便说一句,我只是在谈论 C++ ;)

关于c++ - (c/c++) 字符串文字的拷贝是否在 TEXT 部分共享内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1870329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com