logo

wspólna_ptr w C++

std::shared_ptr to jeden z inteligentnych wskaźników wprowadzonych w C++ 11. W przeciwieństwie do prostego wskaźnika, ma on powiązany blok kontrolny, który śledzi liczbę odwołań dla zarządzanego obiektu. Ta liczba odwołań jest współdzielona pomiędzy wszystkimi kopiami instancji Shared_ptr wskazującymi na ten sam obiekt, zapewniając prawidłowe zarządzanie pamięcią i usuwanie.

Warunki wstępne: Wskaźniki w C++ , Inteligentne wskaźniki w C++ .



wspólna_ptr-w-CPP

Udostępniony wskaźnik w C++

Składnia std::shared_ptr

Shared_ptr typu T można zadeklarować jako:

  std::shared_ptr      ptr_name;>

Inicjalizacja obiektów udostępnionych_ptr

Możemy zainicjować Shared_ptr za pomocą następujących metod:



1. Inicjalizacja przy użyciu nowego wskaźnika

shared_ptr ptr (new T()); shared_ptr ptr = make_shared (new T());>

2. Inicjalizacja przy użyciu istniejącego wskaźnika

shared_ptr ptr(already_existing_pointer); shared_ptr ptr = make_shared(already_existing_pointer);>

Metody członkowskie udostępnionego_ptr

Poniżej znajdują się niektórzy członkowie powiązani z Shared_ptr:



metoda Opis
Resetowanie() Resetuje std::shared_ptr do pustego, zwalniając własność zarządzanego obiektu.
liczba_użyć() Zwraca bieżącą liczbę odwołań, wskazując, ile instancji std::shared_ptr ma współwłasność.
unikalny() Sprawdź, czy istnieje tylko jeden std::shared_ptr będący właścicielem obiektu (liczba odwołań wynosi 1).
Dostawać() Zwraca surowy wskaźnik do zarządzanego obiektu. Podczas stosowania tej metody należy zachować ostrożność.
zamień(shr_ptr2) zamienia zawartość (własność) dwóch instancji std::shared_ptr.

Przykłady std::shared_ptr

Przykład 1:

C++




// C++ program to demonstrate shared_ptr> #include> #include> using> namespace> std;> class> A {> public>:> >void> show() { cout << 'A::show()' << endl; }> };> int> main()> {> >// creating a shared pointer and accessing the object> >shared_ptr p1(> new> A);> >// printting the address of the managed object> >cout << p1.get() << endl;> >p1->pokaż();> > >// creating a new shared pointer that shares ownership> >shared_ptr> p2(p1);> >p2->pokaż();> > >// printing addresses of P1 and P2> >cout << p1.get() << endl;> >cout << p2.get() << endl;> > >// Returns the number of shared_ptr objects> >// referring to the same managed object.> >cout << p1.use_count() << endl;> >cout << p2.use_count() << endl;> > >// Relinquishes ownership of p1 on the object> >// and pointer becomes NULL> >p1.reset();> >cout << p1.get() << endl;> >cout << p2.use_count() << endl;> >cout << p2.get() << endl;> >/*> >These lines demonstrate that p1 no longer manages an> >object (get() returns nullptr), but p2 still manages the> >same object, so its reference count is 1.> >*/> >return> 0;> }>

>

>

Wyjście

0x1365c20 A::show() A::show() 0x1365c20 0x1365c20 2 2 0 1 0x1365c20>

Przykład 2:

C++




// C++ program to illustrate the use of make_shared> #include> #include> using> namespace> std;> int> main()> {> >// Creating shared pointers using std::make_shared> >shared_ptr<>int>>shr_ptr1 = make_shared<>int>>(42);> >shared_ptr<>int>>shr_ptr2 = make_shared<>int>>(24);> >// Accessing the values using the dereference operator> >// (*)> >cout << 'Value 1: ' << *shr_ptr1 << endl;> >cout << 'Value 2: ' << *shr_ptr2 << endl;> >// Using the assignment operator (=) to share ownership> >shared_ptr<>int>>shr_ptr3 = shr_ptr1;> >// Checking if shared pointer 1 and shared pointer 3> >// point to the same object> >if> (shr_ptr1 == shr_ptr3) {> >cout << 'shared pointer 1 and shared pointer 3 '> >'point to the same object.'> ><< endl;> >}> >// Swapping the contents of shared pointer 2 and shared> >// pointer 3> >shr_ptr2.swap(shr_ptr3);> >// Checking the values after the swap> >cout << 'Value 2 (after swap): ' << *shr_ptr2 << endl;> >cout << 'Value 3 (after swap): ' << *shr_ptr3 << endl;> >// Using logical operators to check if shared pointers> >// are valid> >if> (shr_ptr1 && shr_ptr2) {> >cout << 'Both shared pointer 1 and shared pointer '> >'2 are valid.'> ><< endl;> >}> >// Resetting a shared pointer> >shr_ptr1.reset();> }>

>

>

Wyjście

Value 1: 42 Value 2: 24 shared pointer 1 and shared pointer 3 point to the same object. Value 2 (after swap): 42 Value 3 (after swap): 24 Both shared pointer 1 and shared pointer 2 are valid.>

Przykład 3: Implementacja listy połączonej za pomocą std::shared_ptr

C++




#include> #include> using> namespace> std;> // Define a singly linked list node> struct> Node {> >int> data;> >shared_ptr next;> >Node(>int> val)> >: data(val)> >, next(NULL)> >{> >}> };> class> LinkedList {> public>:> >LinkedList()> >: head(NULL)> >{> >}> >// Insert a new node at the end of the linked list> >void> insert(>int> val)> >{> >shared_ptr newNode = make_shared(val);> >if> (!head) {> >head = newNode;> >}> >else> {> >shared_ptr current = head;> >while> (current->następny) {> >current = current->następny;> >}> >current->następny = nowyWęzeł;> >}> >}> >// Delete a node with a given value from the linked list> >void> del(>int> val)> >{> >if> (!head) {> >return>;> >}> >if> (head->dane == wartość) {> >head = head->następny;> >return>;> >}> >shared_ptr current = head;> >while> (current->następny> >&& current->następny->dane != wartość) {> >current = current->następny;> >}> >if> (current->następny && bieżący->następny->dane == wartość) {> >current->następny = bieżący->następny->następny;> >}> >}> >// Traverse and print the linked list> >void> Print()> >{> >shared_ptr current = head;> >while> (current) {> >cout current = current->Następny; } cout<< 'NULL' << endl; } private: shared_ptr head; }; int main() { LinkedList linkedList; // Insert nodes into the linked list linkedList.insert(1); linkedList.insert(2); linkedList.insert(3); // Print the linked list cout << 'Linked List: '; linkedList.Print(); // Delete a node and print the updated linked list linkedList.del(2); cout << 'Linked List after deleting 2: '; linkedList.Print(); return 0; }>

>

dfs kontra bfs

>

Wyjście

Linked List: 1 ->2 -> 3 -> NULL Lista połączona po usunięciu 2: 1 -> 3 -> NULL>