我的问题可以归结为,字符串从stringstream.str().c_str()内存中返回的字符串在哪里,为什么不能将其分配给const char*?
这个代码示例将比我更好地解释它
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
stringstream ss("this is a string\n");
string str(ss.str());
const char* cstr1 = str.c_str();
const char* cstr2 = ss.str().c_str();
cout << cstr1 // Prints correctly
<< cstr2; // ERROR, prints out garbage
system("PAUSE");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
stringstream.str().c_str()可以分配给a 的假设const char*导致我花了一段时间追踪的错误.
对于奖励积分,任何人都可以解释为什么替换cout声明
cout << cstr // Prints correctly
<< ss.str().c_str() // Prints correctly
<< cstr2; // Prints correctly (???)
Run Code Online (Sandbox Code Playgroud)
正确打印字符串? …
在提出这个问题的时候,我学会了对一个临时对象的const引用在C++中是有效的:
int main ()
{
int a = 21;
int b = 21;
//error: invalid initialization of non-const reference
//int & sum = a + b;e [...]
//OK
int const & sum = a + b;
return sum;
}
Run Code Online (Sandbox Code Playgroud)
但在下面的示例中,const引用refnop引用了一个被销毁的临时对象.我想知道为什么?
#include <string>
#include <map>
struct A
{
// data
std::map <std::string, std::string> m;
// functions
const A& nothing() const { return *this; }
void init() { m["aa"] = "bb"; }
bool operator!= (A const& a) const …Run Code Online (Sandbox Code Playgroud)