parent
0bac4dbfd9
commit
bc3790efd3
@ -0,0 +1,48 @@ |
||||
#include <string> |
||||
#include <memory> |
||||
#include <iostream> |
||||
|
||||
using std::string, std::unique_ptr, |
||||
std::shared_ptr, std::make_unique; |
||||
|
||||
class BadRef { |
||||
string &name; |
||||
|
||||
public: |
||||
BadRef(string &name) : name(name) {} |
||||
|
||||
void set_name(string &n) { |
||||
name = n; |
||||
} |
||||
}; |
||||
|
||||
class GoodRef { |
||||
string *name; |
||||
|
||||
public: |
||||
/*
|
||||
* After calling, name is owned. |
||||
*/ |
||||
GoodRef(string *n) : name(n) {} |
||||
|
||||
void print() { |
||||
std::cout << "My name is " << *name << std::endl; |
||||
} |
||||
}; |
||||
|
||||
int main() { |
||||
string my_name = "Zed"; |
||||
string your_name = "Alex"; |
||||
string &ref_test = my_name; |
||||
string *ptr_name = new string("Pointer"); |
||||
|
||||
ref_test = your_name; |
||||
|
||||
auto br = BadRef(my_name); |
||||
br.set_name(your_name); |
||||
|
||||
auto gr = GoodRef(ptr_name); |
||||
gr.print(); |
||||
|
||||
return 0; |
||||
} |
Loading…
Reference in new issue