看板 C_and_CPP 關於我們 聯絡資訊
請問shared_ptr 有辦法new 動態二維陣列嗎? 原本的 C code : int** p = new int* [3]; for(int i = 0; i < 3; i++) { p[i] = new int [i+1]; } 結果會產生一個2維陣列 [] [][] [][][] 如果現在要改成 shared_ptr,要怎麼做呢? std::shared_ptr<int*> q( new int* [3], []( int **q ) { delete[] *q; } ); for(int i = 0; i < 3; i++) { q.get()+i = shared_ptr<int>(new int[i+1], []( int *q ) { delete[] q; } ); } compile的結果是... cannot convert from 'std::shared_ptr<int>' to 'int **' 不過我改不出正確的結果...有人知道要怎麼寫嗎? 還是我這種用法不對? 有其他的STL可以實現這樣的功能嗎? 先謝過了~m(_ _)m -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.136.126.41 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1421745666.A.973.html ※ 編輯: everydate (223.136.126.41), 01/20/2015 17:23:13
Killercat: 換我我不會那麼搞剛 我會用std::vector<std::vector>> 01/20 17:41
kwpn: smart pointer通常被用來指向一個物件, 雖然也可以指向陣列, 01/20 17:45
kwpn: 但陣列可用vector取代, 不太會去用smart pointer. 01/20 17:46
anyoiuo: http://goo.gl/fn6tXu 01/21 19:00
wuliou: 雙重vector比較快 01/21 20:56
legendmtg: 別亂拿shared_ptr去指operator new[]生出來的陣列... 01/21 21:40
legendmtg: 他只會call delete不會call delete[].... 01/21 21:41
legendmtg: 用vector當然最好 但如果真的要用到陣列該用 01/21 21:42
legendmtg: boost::shared_array 01/21 21:42