C 怎樣對任意乙個儲存指標型別的tuple釋放其所有指標指向的空間?

時間 2021-06-03 09:14:20

1樓:暮無井見鈴

C++14 ver.

#include

#include

#include

template

T>std::

enable_if_t

is_pointer

::

value

&&std

::is_object

remove_pointer_t

>::

value

>delete_raw_ptr(T

const

&ptr

)template

T>std::

enable_if_t

std::

is_pointer

::

value||!

std::

is_object

remove_pointer_t

>::

value

>delete_raw_ptr(T

const&)

{}template

Tup,

std::

size_t

...Idx

>void

delete_raw_ptr_in_tuple_help(Tup

const

&tpl

,std

::integer_sequence

size_t

,Idx

...>);

// consume results

(void

)arr;}

template

Tup>

void

delete_raw_ptr_in_tuple(Tup

const

&tpl));

}C++17 ver.

#include

#include

template

Tup>

void

delete_raw_ptr_in_tuple(Tup

const

&tpl);

std::([

=](auto

const

&...ps)

,tpl);}

不過最好還是不要這樣寫。你不一定能確定某個 tuple 中的裸指標值都是 new 出來的。

(更正了之前的錯誤用法)

2樓:yc znone

get_tuple_elm這個函式最好返回裸指標,因為使用者不應該釋放這個指標。因為unique_ptr不可以複製,auto做為返回值需要複製語義,所以出錯,應該用decltype(auto)。

C 中如何判斷乙個變數的型別是否為指標?

我覺得題主應該是之前學過某種動態型別的語言 比如python js 想要學C C 於是才會有這個疑問吧?C或者C 屬於靜態型別語言,你一般不會遇到這個問題,至少目前應該是不會,因為乙個變數在傳遞過程中你必須要明確他的型別,那你怎麼可能不知道它是不是指標?比如說你在題目中說的 fun A 在C和C 中...

C 中能否將指標理解成乙個「儲存」引用的記憶體空間?

白東傑 不可以。引用沒有對應的記憶體上的模型,而是乙個抽象的語法概念。你的疑惑發生在 decltype 上。decltype 會完整地複製引數的型別,包括 和 const。如果不想要,可以寫 remove reference type。詳細的可以看 effective modern c 不過在那之前...

C 中 可以將 不同型別的函式指標 放在 同乙個vector中嗎?

劉春雷 我覺得可以這樣子,對於引數不同的函式 方法1 假如有2個函式fun1,fun2 這兩個函式的引數不同,可以利用多型將這兩個函式變成相同的格式 std string fun1 std string str1 std string fun2 std string str1,std string ...