Using References as member variables
Hi,
I am just in the process of changing some classes in my program to have references instead of pointers as member variables. One idea behind it is that it should not be able to initialize any member of the class with a null pointer.
However I came at some point to realize that references can be as dangerous as pointers. Below is some code which dumps core on the last line, for obvious reasons.
Code:
#include <string>
#include <iostream>
class T
{
public:
T( std::string& s )
: _s( s ) {};
void print() { std::cout << _s << std::endl; }
private:
std::string& _s;
};
int main()
{
T * myobj = 0;
try {
// Creating a string on the stack
std::string stackstring( "Hello World!" );
myobj = new T( stackstring );
myobj->print();
// Checking if myobj really contains a reference
stackstring = "Hello Mom!";
myobj->print();
}
catch ( ... ) {
delete myobj;
throw;
}
if ( myobj ) {
// myobj still exists but stackstring not
myobj->print();
}
}
Now does anybody know of some magic tricks to avoid these kind of problems? I can only think of making _s a pointer again and checking if it is 0 each time before accessing it.
Thanks for any thoughts on this subject.