當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C++ shared_ptr用法及代碼示例


std::shared_ptr是C++11中引入的智能指針之一。與簡單指針不同,它有一個關聯的控製塊,用於跟蹤托管對象的引用計數。此引用計數在指向同一對象的 shared_ptr 實例的所有副本之間共享,確保正確的內存管理和刪除。

先決條件: C++ 中的指針,C++ 中的智能指針.

shared_ptr-in-CPP

C++ 中的共享指針

std::shared_ptr 的語法

T 類型的 shared_ptr 可以聲明為:

std::shared_ptr <T> ptr_name;

shared_ptr對象的初始化

我們可以使用以下方法初始化shared_ptr:

1. 使用新指針進行初始化

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

2.使用現有Pointer進行初始化

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

shared_ptr的成員方法

以下是與shared_ptr相關的一些成員:

方法 說明
reset() 將 std::shared_ptr 重置為空,釋放托管對象的所有權。
use_count() 返回當前引用計數,指示有多少個 std::shared_ptr 實例共享所有權。
unique() 檢查是否隻有一個 std::shared_ptr 擁有該對象(引用計數為 1)。
get() 返回指向托管對象的原始指針。使用此方法時要小心。
交換(shr_ptr2) 交換兩個 std::shared_ptr 實例的內容(所有權)。

std::shared_ptr 的示例

示例 1:

C++


// C++ program to demonstrate shared_ptr
#include <iostream>
#include <memory>
using namespace std;
class A {
public:
    void show() { cout << "A::show()" << endl; }
};
int main()
{
    // creating a shared pointer and accessing the object
    shared_ptr<A> p1(new A);
    // printting the address of the managed object
    cout << p1.get() << endl;
    p1->show();
   
    // creating a new shared pointer that shares ownership
    shared_ptr<A> p2(p1);
    p2->show();
   
    // 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;
}
輸出
0x1365c20
A::show()
A::show()
0x1365c20
0x1365c20
2
2
0
1
0x1365c20

示例 2:

C++


// C++ program to illustrate the use of make_shared
#include <iostream>
#include <memory>
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 <iostream>
#include <memory>
using namespace std;
// Define a singly linked list node
struct Node {
    int data;
    shared_ptr<Node> 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<Node> newNode = make_shared<Node>(val);
        if (!head) {
            head = newNode;
        }
        else {
            shared_ptr<Node> current = head;
            while (current->next) {
                current = current->next;
            }
            current->next = newNode;
        }
    }
    // Delete a node with a given value from the linked list
    void del(int val)
    {
        if (!head) {
            return;
        }
        if (head->data == val) {
            head = head->next;
            return;
        }
        shared_ptr<Node> current = head;
        while (current->next
               && current->next->data != val) {
            current = current->next;
        }
        if (current->next && current->next->data == val) {
            current->next = current->next->next;
        }
    }
    // Traverse and print the linked list
    void Print()
    {
        shared_ptr<Node> current = head;
        while (current) {
            cout << current->data << " -> ";
            current = current->next;
        }
        cout << "NULL" << endl;
    }
private:
    shared_ptr<Node> 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
Linked List after deleting 2: 1 -> 3 -> NULL


相關用法


注:本文由純淨天空篩選整理自yash_cse_21大神的英文原創作品 shared_ptr in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。