#include #include #include using namespace std; class stack{ struct node { // узел списка (с печатью что происходит) int value; shared_ptr next; // ссылка на следующий node(int x, shared_ptr n) { value = x; next = n; cout << "node " << this << endl; } ~node() { cout << "~node " << this << endl; } }; shared_ptr top; // указатель на вершину стека public: stack() : top() { /*top = nullptr;*/ } void push(int x) { top = make_shared(x, top); } bool pop (int &x) { if (!top) return false; shared_ptr p = top; x = top->value; top = top->next; return true; } friend ostream & operator<<(ostream &os, const stack &s); }; // полная распечатка стека ostream & operator<<(ostream &os, const stack &s) { os << "stack\n"; for (auto p = s.top; p; p = p->next) os << " " << p->value; os << "\n--------\n"; return os; } // класс для демонстрации других свойств struct sp { int x; sp(int xx) { x = xx; cout << "sp " << this << endl; } ~sp() {cout << "~sp " << this << endl; } }; // функция, которая что-то делает с указателем shared_ptr f(shared_ptr q) { (q->x)++; return q; } int main() { int x; stack s; s.push(1); s.push(2); s.push(3); s.push(4); cout << s; s.pop(x); s.pop(x); cout << s; // создание и присваивание cout << "\ncreate and assign -------------\n"; shared_ptr p1(new sp(10)); shared_ptr p2; p2 = f(p1); // массив указателей cout << "\narray of pointers -------------\n"; vector> v(10); for (int i=0; i<5; i++) { // меньше чем длина !!! v[i] = make_shared(i); } return 0; }