Crash on accessing reference to string
This code crashes at the cout line. Can anyone explain why this doesn't work?
#include <iostream>
#include <string>
u开发者_运维百科sing namespace std;
class myclass {
const string& m_str;
public:
myclass(string s) : m_str(s) {}
const string& getString() const { return m_str; }
};
int main () {
const string str("honey");
myclass mc(str);
cout << mc.getString() << "\n";
return 0;
}
the myclass
constructor is taking a string by value which makes it a temporary. You're then binding this temporary to the m_str
member. As soo as the constructor exits your member reference becomes invalid. Instead: myclass(const string& s) : m_str(s) {}
Even so that may not be a good idea. Generally speaking using references as members can be dangerous because you have to be very clear about lifetime semantics. You should consider just storing the string by value in your class unless you have a specific reason not to do so.
精彩评论