日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

C++特性之智能指針shared_ptr詳解_C 語言

作者:明月醉窗臺 ? 更新時間: 2023-01-03 編程語言

shared_ptr 是C++11提供的一種智能指針類,它足夠智能,可以在任何地方都不使用時自動刪除相關指針,從而幫助徹底消除內(nèi)存泄漏和懸空指針的問題。

它遵循共享所有權的概念,即不同的 shared_ptr 對象可以與相同的指針相關聯(lián),并在內(nèi)部使用引用計數(shù)機制來實現(xiàn)這一點。

每個 shared_ptr 對象在內(nèi)部指向兩個內(nèi)存位置:

1、指向?qū)ο蟮闹羔槨?/p>

2、用于控制引用計數(shù)數(shù)據(jù)的指針。

共享所有權如何在參考計數(shù)的幫助下工作:

1、當新的 shared_ptr 對象與指針關聯(lián)時,則在其構造函數(shù)中,將與此指針關聯(lián)的引用計數(shù)增加1。

2、當任何 shared_ptr 對象超出作用域時,則在其析構函數(shù)中,它將關聯(lián)指針的引用計數(shù)減1。如果引用計數(shù)變?yōu)?,則表示沒有其他 shared_ptr 對象與此內(nèi)存關聯(lián),在這種情況下,它使用delete函數(shù)刪除該內(nèi)存。

1.創(chuàng)建指針對象

使用原始指針創(chuàng)建 shared_ptr 對象

std::shared_ptr<int> p1(new int());

???????//檢查shared_ptr對象的引用計數(shù)
p1.use_count();

上面這行代碼在堆上創(chuàng)建了兩塊內(nèi)存:1:存儲int。2:用于引用計數(shù)的內(nèi)存,管理附加此內(nèi)存的 shared_ptr 對象的計數(shù),最初計數(shù)將為1。

for ex:

#include <iostream>
#include <memory>

struct C {int* data;};

int main () {
 auto deleter = [](int*p){
    std::cout << "[deleter called]\n"; delete p;
  };//Labmbda表達式

  std::shared_ptr<int> p1;//默認構造,沒有獲取任何指針的所有權,引用計數(shù)為0
  std::shared_ptr<int> p2 (nullptr);//同1
  std::shared_ptr<int> p3 (new int);//擁有指向int的指針所有權,引用計數(shù)為1
  std::shared_ptr<int> p4 (new int, deleter);//作用同3,但是擁有自己的析構方法,如果指針所指向?qū)ο鬄閺碗s結構C
                                    //結構C里有指針,默認析構函數(shù)不會將結構C里的指針data所指向的內(nèi)存釋放,這時需要自己使用自己的析構函數(shù)(刪除器)
  std::shared_ptr<int> p5 (new int, [](int* p){delete p;}, std::allocator<int>());//同4,但擁有自己的分配器(構造函數(shù)),如成員中有指針,可以為指針分配內(nèi)存,原理跟淺拷貝和深拷貝類似
  std::shared_ptr<int> p6 (p5);//如果p5引用計數(shù)不為0,則引用計數(shù)加1,否則同樣為0
  std::shared_ptr<int> p7 (std::move(p6));//獲取p6的引用計數(shù),p6引用計數(shù)為0
  std::shared_ptr<int> p8 (std::unique_ptr<int>(new int));//p8獲取所有權,引用計數(shù)設置為1
  std::shared_ptr<C> obj (new C);
  std::shared_ptr<int> p9 (obj, obj->data);//同6一樣,只不過擁有自己的刪除器與4一樣

  std::cout << "use_count:\n";
  std::cout << "p1: " << p1.use_count() << '\n';
  std::cout << "p2: " << p2.use_count() << '\n';
  std::cout << "p3: " << p3.use_count() << '\n';
  std::cout << "p4: " << p4.use_count() << '\n';
  std::cout << "p5: " << p5.use_count() << '\n';
  std::cout << "p6: " << p6.use_count() << '\n';
  std::cout << "p7: " << p7.use_count() << '\n';
  std::cout << "p8: " << p8.use_count() << '\n';
  std::cout << "p9: " << p9.use_count() << '\n';
  return 0;
}
/*
Output:
use_count:
p1: 0
p2: 0
p3: 1
p4: 1
p5: 2
p6: 0
p7: 2
p8: 1
p9: 2
*/

創(chuàng)建空的 shared_ptr 對象,因為帶有參數(shù)的 shared_ptr 構造函數(shù)是 explicit 類型的,所以不能像這樣std::shared_ptr<int> p1 = new int();隱式調(diào)用它構造函數(shù)。創(chuàng)建新的shared_ptr對象的最佳方法是使用std :: make_shared:

std::shared_ptr<int> p1 = std::make_shared<int>();

std::make_shared 一次性為int對象和用于引用計數(shù)的數(shù)據(jù)都分配了內(nèi)存,而new操作符只是為int分配了內(nèi)存。

賦值:

#include <iostream>
#include <memory>

int main () {
  std::shared_ptr<int> foo;
  std::shared_ptr<int> bar (new int(10));

  foo = bar;                          // 拷貝,引用計數(shù)加1

  bar = std::make_shared<int> (20);   // 移動
//unique_ptr 不共享它的指針。它無法復制到其他 unique_ptr,無法通過值傳遞到函數(shù),也無法用于需要副本的任何標準模板庫 (STL) 算法。只能移動unique_ptr
  std::unique_ptr<int> unique (new int(30));
  foo = std::move(unique);            // move from unique_ptr,引用計數(shù)轉移

  std::cout << "*foo: " << *foo << '\n';
  std::cout << "*bar: " << *bar << '\n';

  return 0;
}
Output:
/*
*foo: 30
*bar: 20
*/

2.分離關聯(lián)的原始指針

要使 shared_ptr 對象取消與相關指針的關聯(lián),可以使用reset()函數(shù):

//不帶參數(shù)的reset(),將引用計數(shù)減少1,如果引用計數(shù)變?yōu)?,則刪除指針
p1.reset();

//帶參數(shù)的reset(),他將內(nèi)部指向新指針,因此其引用計數(shù)將再次變?yōu)?
p1.reset(new int(34));

//使用nullptr重置:
p1=nullptr
#include <iostream>
#include  <memory> // 需要包含這個頭文件

int main()
{
	// 使用 make_shared 創(chuàng)建空對象
	std::shared_ptr<int> p1 = std::make_shared<int>();
	*p1 = 78;
	std::cout << "p1 = " << *p1 << std::endl; // 輸出78

	// 打印引用個數(shù):1
	std::cout << "p1 Reference count = " << p1.use_count() << std::endl;

	// 第2個 shared_ptr 對象指向同一個指針
	std::shared_ptr<int> p2(p1);

	// 下面兩個輸出都是:2
	std::cout << "p2 Reference count = " << p2.use_count() << std::endl;
	std::cout << "p1 Reference count = " << p1.use_count() << std::endl;

	// 比較智能指針,p1 等于 p2
	if (p1 == p2) {
		std::cout << "p1 and p2 are pointing to same pointer\n";
	}

	std::cout<<"Reset p1 "<<std::endl;

	// 無參數(shù)調(diào)用reset,無關聯(lián)指針,引用個數(shù)為0
	p1.reset();
	std::cout << "p1 Reference Count = " << p1.use_count() << std::endl;
	
	// 帶參數(shù)調(diào)用reset,引用個數(shù)為1
	p1.reset(new int(11));
	std::cout << "p1  Reference Count = " << p1.use_count() << std::endl;

	// 把對象重置為NULL,引用計數(shù)為0
	p1 = nullptr;
	std::cout << "p1  Reference Count = " << p1.use_count() << std::endl;
	if (!p1) {
		std::cout << "p1 is NULL" << std::endl; // 輸出
	}
	return 0;
}

3.與普通指針比較

缺少 ++, – – 和 [] 運算符

與普通指針相比,shared_ptr僅提供-> 、*和==運算符,沒有+、-、++、–、[]等運算符。

#include<iostream>
#include<memory>

struct Sample {
	void dummyFunction() {
		std::cout << "dummyFunction" << std::endl;
	}
};

int main()
{

	std::shared_ptr<Sample> ptr = std::make_shared<Sample>();

	(*ptr).dummyFunction(); // 正常
	ptr->dummyFunction(); // 正常

	// ptr[0]->dummyFunction(); // 錯誤方式
	// ptr++;  // 錯誤方式
	//ptr--;  // 錯誤方式

	std::shared_ptr<Sample> ptr2(ptr);
	if (ptr == ptr2) // 正常
		std::cout << "ptr and ptr2 are equal" << std::endl;
	return 0;
}

4.NULL檢測

當我們創(chuàng)建 shared_ptr 對象而不分配任何值時,它就是空的;普通指針不分配空間的時候相當于一個野指針,指向垃圾空間,且無法判斷指向的是否是有用數(shù)據(jù)。

std::shared_ptr<Sample> ptr3;
if(!ptr3)
    std::cout<<"Yes, ptr3 is empty" << std::endl;
if(ptr3 == NULL)
    std::cout<<"ptr3 is empty" << std::endl;
if(ptr3 == nullptr)
    std::cout<<"ptr3 is empty" << std::endl;

原文鏈接:https://blog.csdn.net/yohnyang/article/details/128118719

欄目分類
最近更新