|
#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; |
|
} |
Output obtained thanks to http://cpp.sh/: