C ++中的指针,智能指针和共享指针
指针
指针用于存储变量的地址。
语法
Type *pointer;
初始化
Type *pointer; Pointer = variable name;
职能
指针用于存储变量的地址。
指针可以分配空值。
指针可以通过引用进行引用。
指针在堆栈上具有其自己的内存地址和大小。
示例
#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