Skip to content

Instantly share code, notes, and snippets.

@w2ak
Created September 5, 2018 12:15
Show Gist options
  • Save w2ak/5b1793332ea7f7c93a47ac645bd321ca to your computer and use it in GitHub Desktop.
Save w2ak/5b1793332ea7f7c93a47ac645bd321ca to your computer and use it in GitHub Desktop.
#include <iostream>
#include <memory>
#include <list>
using namespace std;
#define SIZE 4
static int GID = 0;
struct X {
int id;
X() : id(GID++) {}
~X() { cerr << "~X[" << id << "]" << endl; }
void foo() const { cout << "X[" << id << "]"; }
};
class uptr : public unique_ptr<X> {
public:
uptr() : unique_ptr<X>() {}
uptr(X * x) : unique_ptr<X>(x) {}
void foo() const { if (!get()) { cout << "NULL"; return; } (*this)->foo(); }
};
class sptr : public shared_ptr<X> {
public:
sptr() : shared_ptr<X>() {}
sptr(X * x) : shared_ptr<X>(x) {}
void foo() const { if (!get()) { cout << "NULL"; return; } (*this)->foo(); }
};
class ulst : public list<uptr> {
private:
int id;
public:
ulst() : list<uptr> () , id(GID++) {}
void append(X * x) { push_back(uptr(x)); }
void append(uptr& p) { push_back(uptr(move(p))); }
void foo() const {
cout << "List[" << id << "]: [";
for (auto b = cbegin(), x = b, e = cend(); x!=e; x++) {
if (x!=b) cout << ", ";
x->foo();
};
cout << "]" << endl;
}
};
class slst : public list<sptr> {
private:
int id;
public:
slst() : list<sptr> () , id(GID++) {}
void append(X * x) { push_back(sptr(x)); }
void append(sptr& p) { push_back(sptr(p)); }
void foo() const {
cout << "List[" << id << "]: [";
for (auto b = cbegin(), x = b, e = cend(); x!=e; x++) {
if (x!=b) cout << ", ";
x->foo();
cout << "#" << x->use_count();
};
cout << "]" << endl;
}
};
int main()
{
cout << "List of Unique Pointers" << endl;
ulst l;
l.foo();
cout << "Fill list with data." << endl;
for (int i=0; i<SIZE; i++) l.append(new X());
l.foo();
cout << "Append odd members of list once again to the list." << endl;
{
auto x = l.begin();
for (int i=0,n=l.size(); i<n; x++,i++) if (i&1) l.append(*x);
}
l.foo();
cout << "EOF" << endl; GID=0;
cout << "List of Shared Pointers" << endl;
slst s;
s.foo();
cout << "Fill list with data." << endl;
for (int i=0; i<SIZE; i++) s.append(new X());
s.foo();
cout << "Append odd members of list once again to the list." << endl;
{
auto x = s.begin();
for (int i=0,n=s.size(); i<n; x++,i++) if (i&1) s.append(*x);
}
s.foo();
cout << "EOF" << endl; GID=0;
return 0;
}
@w2ak
Copy link
Author

w2ak commented Sep 5, 2018

Output obtained thanks to http://cpp.sh/:

List of Unique Pointers
List[0]: []
Fill list with data.
List[0]: [X[1], X[2], X[3], X[4]]
Append odd members of list once again to the list.
List[0]: [X[1], NULL, X[3], NULL, X[2], X[4]]
EOF
List of Shared Pointers
List[0]: []
Fill list with data.
List[0]: [X[1]#1, X[2]#1, X[3]#1, X[4]#1]
Append odd members of list once again to the list.
List[0]: [X[1]#1, X[2]#2, X[3]#1, X[4]#2, X[2]#2, X[4]#2]
EOF

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment