Skip to content

Instantly share code, notes, and snippets.

@rightson
Last active October 22, 2015 06:30
Show Gist options
  • Save rightson/e3c05ee9216afc7bfd80 to your computer and use it in GitHub Desktop.
Save rightson/e3c05ee9216afc7bfd80 to your computer and use it in GitHub Desktop.
Take care of your member reference variables
#include <iostream>
#include <string>
class Person {
public:
Person(std::string& reference): _reference(reference) {}
std::string name() { return _reference; }
private:
std::string &_reference;
};
Person* callMeMicky(Person* person) {
std::string name("micky");
person = new Person(name);
if (!person) {
std::cout << "failed to make you micky" << std::endl;
}
return person;
}
int main() {
Person *mick = NULL;
mick = callMeMicky(mick);
if (mick) {
std::cout << "callMeMicky: " << mick->name() << std::endl;
std::cout << "above name does not exist since its reference is destructed after callMeMicky returned" << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment