unique ptr指定刪除器

2021-09-30 01:40:05 字數 1304 閱讀 8696

unique_ptr指定刪除器有幾種方式:

預設刪除器std::default_delete

普通函式

std::function(lambda表示式)

仿函式

普通函式

#include

#include

#include

intmain()

);ptr[9]

=9;}

getchar()

;return0;

}

上面的寫法在lambda沒有捕獲變數的情況下是正確的,如果捕獲了變數,就會報錯:

將**修改為:

std:

:unique_ptr<

int,

void(*

)(int*

)>

ptr(new int[10

],[&

](int*p)

);

嚴重性 ** 說明 專案 檔案 行 禁止顯示狀態

錯誤 c2664 「std::unique_ptr::unique_ptr(const std::unique_ptr&)」: 無法將引數 2 從「main::」轉換為「const _dx &」 unique_ptr_demo e:\vs_project\unique_ptr_demo\unique_ptr_demo\main.cpp 8

這是因為lambda在沒有捕獲變數的情況下是可以直接轉換成函式指標的,一旦捕獲了,就無法轉換。用下面的方法可以在刪除器中使用lambda,並且支援捕獲變數。

另外:

std:

:shared_ptr<

int[

]>

ptr(new int[10

],(int

*p))

;

是合法的,不會報錯。

std::functional

#include

#include

#include

intmain()

);ptr[9]

=9;}

getchar()

;return0;

}

使用仿函式
#include

#include

#include

struct mydeleter};

intmain()

getchar()

;return0;

}

參考:

刪除指定程序

include cstring str,prcnum processentry32 processinfo 宣告程序資訊變數 processinfo.dwsize sizeof processinfo 設定processinfo的大小 返回系統中第乙個程序的資訊 bool status proces...

刪除指定字元

題目 刪除字串中的 b 和 ac 需要滿足如下的條件 例如 進一步思考 如何處理aaccac呢,需要做哪些改變呢?分析 首先要明白從字串中刪除某些字元該如何實現,顯而易見我們可以把保留的字元拷貝新的字串中來實現刪除。但是題目要求不能使用額外的空間。那就是將要刪除的字元全部交換到字串的尾部,然後設定乙...

C C 刪除指定目錄

用到shlwapi.h和tchar.h標頭檔案。shlwapi.h是shlwapi.dll標頭檔案,shlwapi.dll microsoft shell light weight utility library 中定義了路徑相關的操作,也包括了部分檔案操作函式。由於shlwapi.dll屬於mic...