常量引用时奇怪的字符串行为
Strange strings behaviour when const reference
当 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 ' ', printing "890123456789"
a.test();
}
只有超过 15 个字符的字符串才会发生这种情况。如果删除类属性中的const &
,我不再有这个问题 我在字符串超过 15 个字符时在其他项目中遇到过代码中的内存泄漏,所以我想知道:
当字符串超过 15 个字符时,到底发生了什么?
str_
是对临时对象的引用。在构造函数的主体中使用 str_
时,临时仍处于活动状态。当您在test
中使用str_
时,临时不再有效。
程序具有未定义的行为。
相关文章:
- Visual c ++,使用字符串引用/指针调用 dll 函数
- 字符串引用参数的效率C++
- C++字符串引用不能共存
- 尝试使用字符串引用已删除的函数
- 设置可变值通过字符串引用它
- std::串联的字符串引用是安全的
- 字符串引用(函数)的差异
- 字符串引用和常量字符指针的函数重载
- 将浮点数分配给字符串引用有效 - 为什么
- 常量字符串引用作为非类型模板参数
- 函数,该函数返回一个字符串引用c++
- 如何实例化C++成员字符串引用
- c++函数返回NULL字符串引用
- 在 C++ 中返回 const 字符串引用的字符串文本
- CPP 中的字符串引用处理
- 为什么我的字符串引用成员变量在C++中设置为空字符串
- 了解返回字符串引用的函数中的"const"
- c++在同一个函数中返回字符串引用和传递字符串引用
- System::对C++char*参数的字符串引用
- 正在更改conststd::字符串引用的referent