對於演繹的原因,我寫了代碼如下:返回類成員引用運行時錯誤變量結果
class Bike
{
public:
Bike(std::string name) : m_name(name) {}
std::string& getName() const { return m_name; }
private:
std::string& m_name;
};
int main() {
string name("Trek");
Bike bike(name);
string& ref1 = name;
string& ref2 = ref1;
string& ref3 = bike.getName(); // <Error reading characters of string> why?
cout << ref1 << endl; // ok
cout << ref2 << endl; // ok too
cout << ref3 << endl; // Boom. runtime error
return 0;
}
能有人請解釋這種行爲背後的原因?