C++C_str()的奇怪行为
C++ c_str() strange behavior
我得到了以下程序:
std::string f() {
return "f";
}
std::string g() {
return "g";
}
int main() {
const char *s = f().c_str();
std::cout << "s = " << s << std::endl;
std::cout << "g() = " << g() << std::endl;
std::cout << "s = " << s << std::endl;
}
我希望看到s总是打印出"f",但下面是我得到的:
s = f
g() = g
s = g
我抓头发好几个小时了,但还是没弄清楚出了什么问题。
您的指针s
在打印时无效,因为对f()
的调用导致的临时std:string
在此时被销毁(销毁发生在main
函数第一行的完整表达式的和处)。
试试这个:
int main() {
std::string f_string = f();
const char *s = f_string.c_str();
std::cout << "s = " << s << std::endl;
std::cout << "g() = " << g() << std::endl;
std::cout << "s = " << s << std::endl;
}
现在,当访问指针时,c_str
所调用的字符串仍在作用域中时,它应该可以工作。
相关文章:
- Python str to C++ to Python str
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- 字符串变量,比如说"字符串str",可以直接复制到数组中吗?
- 解释一下 for (char c : str) 的作用?
- 返回 str vs. str.substr(0,str.size()) 在 leetcode 中给了我不同的输出
- remove(str.begin(), str.end(), );无法正常工作(我正在使用视觉工作室 2012)
- Getline(cin,str)的奇怪输出
- 比使用 s.str().c_str() 更好的表达?
- 除以 str.length() 什么也没显示
- 没有'str'成员在 GCC 和 Clang 'std::basic_ostream<char>',但 MSVC 没有问题
- 我可以得到一个字符 * 到一个 std::sregex_iterator 匹配 str() 吗?
- C6001:使用单元化内存"str[i]"
- 而(getline(fin,str)){}即使在到达eof之后仍在处理数据
- 在给定的代码中,有人可以解释一下(int i = 0; i<len; i++)count[str[i]]++的代码片段;
- 在函数内部传递字符 *str
- rdbuf()->str()在哪里?
- std::smatch str() 未返回正确的字符串
- 这是 boost::filesystem 中的错误吗?为什么 boost::filesystem::p ath::str
- STR这个实现是否安全且可移植?
- 'for (auto c : str)' c到底是什么?