C++中的指標、智慧指標和共享指標
指標
指標用於儲存變數的地址。
語法
Type *pointer;
初始化
Type *pointer; Pointer = variable name;
函式
- 指標用於儲存變數的地址。
- 指標可以賦值為null值。
- 指標可以透過引用傳遞進行引用。
- 指標在棧上擁有自己的記憶體地址和大小。
示例
#include <iostream>
using namespace std;
int main() {
// A normal integer variable
int a = 7;
// A pointer variable that holds address of a.
int *p = &a;
// Value stored is value of variable "a"
cout<<"Value of Variable : "<<*p<<endl;
// It will print the address of the variable "a"
cout<<"Address of Variable : "<<p<<endl;
// reassign the value.
*p = 6;
cout<<"Value of the variable is now: "<<*p<<endl;
return 0;
}輸出
Value of Variable : 7 Address of Variable : 0x6ffe34 Value of the variable is now: 6
C++中的智慧指標
智慧指標是一種抽象資料型別,我們可以用它來建立一個普通的指標,使其能夠像檔案處理、網路套接字等一樣進行記憶體管理,它還可以執行許多操作,例如自動銷燬、引用計數等。
在C++中,智慧指標可以實現為模板類,它過載了*和->運算子。auto_ptr、shared_ptr、unique_ptr和weak_ptr是C++庫可以實現的智慧指標形式。
示例
#include<iostream>
using namespace std;
// A generic smart pointer class
template <class T>
class Smartpointer {
T *p; // Actual pointer
public:
// Constructor
Smartpointer(T *ptr = NULL) {
p = ptr;
}
// Destructor
~Smartpointer() {
delete(p);
}
// Overloading dereferencing operator
T & operator * () {
return *p;
}
// Overloding arrow operator so that members of T can be accessed
// like a pointer
T * operator -> () {
return p;
}
};
int main() {
Smartpointer<int> p(new int());
*p = 26;
cout << "Value is: "<<*p;
return 0;
}輸出
Value is: 26
C++中的共享指標
shared_ptr是C++庫可以實現的一種智慧指標形式。它是一個原始指標的容器和一個引用計數(一種儲存對資源(如物件、記憶體塊、磁碟空間或其他資源)的引用、指標或控制代碼數量的技術)所有權結構,與shared_ptr的所有副本協同工作。
只有當shared_ptr的所有副本都被銷燬時,被包含的原始指標引用的物件才會被銷燬。
示例
#include<iostream>
#include<memory>
using namespace std;
int main() {
shared_ptr<int> ptr(new int(7));
shared_ptr<int> ptr1(new int(6));
cout << ptr << endl;
cout << ptr1 << endl;
// Returns the number of shared_ptr objects
// referring to the same managed object.
cout << ptr.use_count() << endl;
cout << ptr1.use_count() << endl;
// Relinquishes ownership of ptr on the object
// and pointer becomes NULL
ptr.reset();
cout << ptr.get() << endl;
cout << ptr1.use_count() << endl;
cout << ptr1.get() << endl;
return 0;
}輸出
0xe80900 0xe80940 1 1 0 1 0xe80940
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP