fork(2) download
  1. #include <iostream>
  2. #include <memory>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. void string_example() {
  8.  
  9. auto a = string("original value");
  10.  
  11. auto b = a; // true copy by copying the value
  12.  
  13. a = string("new value");
  14.  
  15. cout << "a = " << a << endl;
  16. cout << "b = " << b << endl;
  17. cout << boolalpha << "&a == &b ? " << (&a==&b) << endl;
  18. }
  19.  
  20. void shared_ptr_example() {
  21.  
  22. auto a = make_shared<string>("original value");
  23.  
  24. auto b = a; // not a copy, just and alias
  25.  
  26. *a = string("new value"); // and this gonna hurt b
  27.  
  28. cout << "a = " << *a << endl;
  29. cout << "b = " << *b << endl;
  30. cout << boolalpha << "&a == &b ? " << (&a==&b) << endl;
  31. }
  32.  
  33. void shared_ptr_to_const_example() {
  34.  
  35. auto a = make_shared<const string>("original value");
  36.  
  37. auto b = a;
  38.  
  39. //*a = string("new value"); // <-- now won't compile
  40. a = make_shared<const string>("new value");
  41.  
  42. cout << "a = " << *a << endl;
  43. cout << "b = " << *b << endl;
  44. cout << boolalpha << "&a == &b ? " << (&a==&b) << endl;
  45. }
  46.  
  47. int main() {
  48.  
  49. cout << "--------------" << endl;
  50. cout << "string example" << endl;
  51. string_example();
  52.  
  53. cout << "------------------" << endl;
  54. cout << "shared_ptr example" << endl;
  55. shared_ptr_example();
  56.  
  57. cout << "---------------------------" << endl;
  58. cout << "shared_ptr to const example" << endl;
  59. shared_ptr_to_const_example();
  60. }
  61.  
Success #stdin #stdout 0s 3436KB
stdin
Standard input is empty
stdout
--------------
string example
a = new value
b = original value
&a == &b ? false
------------------
shared_ptr example
a = new value
b = new value
&a == &b ? false
---------------------------
shared_ptr to const example
a = new value
b = original value
&a == &b ? false