shared_ptr у C++
std::shared_ptr є одним із розумних покажчиків, представлених у C++11. На відміну від простого покажчика, він має пов’язаний блок керування, який відстежує кількість посилань для керованого об’єкта. Цей підрахунок посилань розподіляється між усіма копіями екземплярів shared_ptr, що вказують на той самий об’єкт, забезпечуючи належне керування пам’яттю та видалення.
Передумови: Покажчики в C++ , Розумні покажчики в C++ .
Спільний покажчик у C++
Синтаксис std::shared_ptr
shared_ptr типу T можна оголосити як:
std::shared_ptr ptr_name;
Ініціалізація об’єктів shared_ptr
Ми можемо ініціалізувати shared_ptr за допомогою таких методів:
1. Ініціалізація за допомогою нового покажчика
shared_ptr ptr (new T()); shared_ptr ptr = make_shared (new T());
2. Ініціалізація за допомогою існуючого покажчика
shared_ptr ptr(already_existing_pointer); shared_ptr ptr = make_shared(already_existing_pointer);
Методи члена shared_ptr
Нижче наведено деяких учасників, пов’язаних із shared_ptr:
| метод | опис |
|---|---|
| reset() | Скидає std::shared_ptr до порожнього, звільняючи право власності на керований об’єкт. |
| use_count() | Повертає поточну кількість посилань, що вказує на те, скільки екземплярів std::shared_ptr спільно володіють. |
| унікальний() | Перевірте, чи є лише один std::shared_ptr власником об’єкта (кількість посилань дорівнює 1). |
| отримати() | Повертає необроблений вказівник на керований об’єкт. Будьте обережні, використовуючи цей метод. |
| swap(shr_ptr2) | міняє вміст (право власності) на два екземпляри std::shared_ptr. |
Приклади std::shared_ptr
приклад 1:
C++
Вихід
0x1365c20 A::show() A::show() 0x1365c20 0x1365c20 2 2 0 1 0x1365c20
приклад 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();> }> |
Вихід
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.
Приклад 3: Реалізація пов’язаного списку за допомогою 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->далі) {> > current = current->далі;> > }> > current->наступний = новийвузол;> > }> > }> > // Delete a node with a given value from the linked list> > void> del(> int> val)> > {> > if> (!head) {> > return> ;> > }> > if> (head->дані == значення) {> > head = head->далі;> > return> ;> > }> > shared_ptr current = head;> > while> (current->далі> > && current->далі->дані != val) {> > current = current->далі;> > }> > if> (current->наступний && поточний->наступний->дані == val) {> > current->наступний = поточний->наступний->наступний;> > }> > }> > // Traverse and print the linked list> > void> Print()> > {> > shared_ptr current = head;> > while> (current) {> > cout current = current->наступний; } 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; }> |
Вихід
Linked List: 1 ->2 -> 3 -> NULL Зв'язаний список після видалення 2: 1 -> 3 -> NULL>