Reputation:
For deductive reasons, I wrote a code as follows:
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;
}
Can someone please explain the reasons behind this behavior?
Upvotes: 0
Views: 63
Reputation: 206597
Can someone please explain the reasons behind this behavior?
You are storing a reference to an object which is not alive after the constructor is finished executing. You are storing a dangling reference.
Bike(std::string name) : m_name(name) {}
^^^^^
name
is a variable on the stack. It is not alive after the function returns.
In order to have a valid reference, the argument to Bike()
has to be passed by reference.
Bike(std::string& name) : m_name(name) {}
^^
Upvotes: 2
Reputation: 103703
Your constructor takes a string by value. So it is a copy that is local to the function. That string is destroyed at the end of the function, making the reference to it invalid. If you want to store a reference to a string in your object (and are you really sure you want to do that?), then you need to make sure the string will outlive the use of the reference. You can do that by changing the constructor parameter to a reference.
Bike(std::string& name) : m_name(name) {}
Although I think it would be better to reconsider whether you should be storing a reference in the first place. It doesn't seem to make much sense here.
Upvotes: 1