Last active
October 22, 2015 06:30
-
-
Save rightson/e3c05ee9216afc7bfd80 to your computer and use it in GitHub Desktop.
Take care of your member reference variables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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