2013-03-26 122 views
0

我需要將三個2D數組合併成一個3D數組。C++將2d數組(合併爲uniqe_ptr)合併到3d數組中

我正在使用unique_ptr引用2D數組。

對於智能指針和一般的C++來說,我很新,所以很可能是一個明顯的錯誤。

int imgsize = 15; 
std::unique_ptr<float[]> redptr(new float[imgsize]); 
std::unique_ptr<float[]> greenptr(new float[imgsize]); 
std::unique_ptr<float[]> blueptr (new float[imgsize]); 

redptr = redChannel._data; 
greenptr = greenChannel._data; 
blueptr = blueChannel._data; 

float * colourArr[3] = {redptr,greenptr,blueptr}; 
+2

我看到這個代碼段沒有任何多維數組。 (也,'std :: vector') – 2013-03-26 15:12:27

+0

[你在做什麼](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)? – 2013-03-26 15:14:35

回答

2

一個 std::unqiue_ptr背後的想法是, std::unique_ptr具有 唯一所有權尖銳的反對。如果發佈的代碼結構與此前提相矛盾,因爲另一個變量現在有指向 std::unique_ptr所擁有的對象的指針。 張貼的代碼是危險的,因爲它是懸空的指針的潛在來源(一旦std::unique_ptr超出範圍爲對象的尖將被破壞但colourArr的元件將仍然指向,現在破壞,對象)。

而不是使用std::unique_ptr而是明確動態分配內存建議使用std::vector<std::vector<float>>來代替。這將管理內存,並提供通過operator[]數組的方式來訪問:

// Construct a vector contain 3 elements, 
// where each element is a vector containing 'imgsize' floats. 
std::vector<std::vector<float>> colourArr(3, std::vector<float>(imgsize)); 
+0

有一個指向唯一指針所擁有的對象的指針是很常見的,並且安全地執行這個操作在大多數程序員的掌握之中。 – Puppy 2013-03-26 15:13:26

+0

感謝您對此的啓發 - 現在看起來合乎邏輯 – mish 2013-03-26 15:17:27

+0

@hmjd:擁有對象的地址決不意味着對所述對象的所有權... – ildjarn 2013-03-26 21:21:31