gpt4 book ai didi

c++ - 常量引用时奇怪的字符串行为

转载 作者:行者123 更新时间:2023-11-28 05:13:12 25 4
gpt4 key购买 nike

当 const 引用字符串超过 15 个字符时,我遇到了一个奇怪的行为。它只是用空字节替换字符串的开头。

Class A
{
public:
A(const std::string& str) : str_(str)
{
std::cout << str_ << std::endl;
}
void test()
{
std::cout << str_ << std::endl;
}
private:
const std::string& str;
};

int main()
{
//printing the full string "01234567890123456789"
A a("01234567890123456789");
//replacing first bytes by '\0', printing "890123456789"
a.test();
}

只有超过 15 个字符的字符串才会出现这种情况。如果删除类属性中的 const & ,我就不会再遇到这个问题了 我在另一个项目中遇到过当字符串超过 15 个字符时我的代码内存泄漏,所以我奇怪:

当字符串超过 15 个字符时到底发生了什么?

最佳答案

str_ 是对临时对象的引用。当您在构造函数的主体中使用 str_ 时,临时对象仍然存在。当您在 test 中使用 str_ 时,临时文件不再存在。

你的程序有未定义的行为。

关于c++ - 常量引用时奇怪的字符串行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43151860/

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