Forgot file, it will go away soon though.

master
Zed A. Shaw 4 months ago
parent 0bac4dbfd9
commit bc3790efd3
  1. 48
      badref.cpp

@ -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…
Cancel
Save