C++ C++;将二维阵列(由uniqe_ptr引用)合并到三维阵列中
我需要将三个二维阵列合并为一个三维阵列 我使用unique_ptr来引用2D数组 一般来说,我对智能指针和C++非常陌生,所以很有可能是一个明显的错误。C++ C++;将二维阵列(由uniqe_ptr引用)合并到三维阵列中,c++,c++11,multidimensional-array,unique-ptr,C++,C++11,Multidimensional Array,Unique Ptr,我需要将三个二维阵列合并为一个三维阵列 我使用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[]> blue
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};
int imgsize=15;
std::unique_ptr redptr(新浮点[imgsize]);
std::unique_ptr greenptr(新浮动[imgsize]);
std::unique_ptr blueptr(新浮点[imgsize]);
redptr=redChannel.\u数据;
greenptr=绿色通道。\ U数据;
blueptr=blueChannel.\u数据;
float*colorArr[3]={redptr、greenptr、blueptr};
std::unqiue_ptr
背后的思想是std::unique_ptr
拥有指向对象的唯一所有权。按照POST的方式构造代码与此前提相矛盾,因为另一个变量现在有一个指向std::unique\u ptr
所拥有对象的指针。发布的代码是危险的,因为它是悬空指针的潜在来源(一旦std::unique_ptr
超出范围,指向的对象将被销毁,但colorarr
的元素仍将指向现在已销毁的对象)
与其使用std::unique_ptr
并显式动态分配内存,不如建议改用。这将通过以下方式管理内存并提供阵列式访问:
//构造一个包含3个元素的向量,
//其中每个元素是一个包含“imgsize”浮动的向量。
std::vector colorarr(3,std::vector(imgsize));
我在这个代码片段中没有看到任何多维数组。(还有,std::vector
)?拥有一个指向唯一指针所拥有的对象的指针是很常见的,而且大多数程序员都能安全地做到这一点。
// 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));