【发布时间】:2019-01-14 20:47:02
【问题描述】:
我一直在尝试使用 boost multi_array_refs,因为它们能够将世界的 2D(在我的情况下)数组视图映射到任意连续内存块上。使用 multi_array_ref,指向连续内存的指针被指定给构造函数。这很好用,但在我的最终应用程序中,我真正想做的是获取一个预先存在的 multi_array_ref 对象,并将其指向稍后动态分配的新缓冲区。看起来这应该是可能的,但我似乎无法弄清楚如何去做。这里有一些框架代码,我希望能展示我正在尝试做的事情的类型,尽管它显然不会像写的那样工作。
const int XSIZE = 10;
const int YSIZE = 5;
typedef boost::multi_array_ref<int, 2> ARRAY_2D_REF;
class Test2D {
public:
Test2D(const int sizeX, const int sizeY);
~Test2D();
// I want to point this multi_array_ref to a buffer that gets
// allocated in the constructor.
ARRAY_2D_REF data;
private:
int xSize;
int ySize;
int *n;
};
// can't construct 'data' using ':' syntax here, because, the 'n'
// buffer has not been allocated yet so 'n' doesn't contain a valid
// address. This compiles okay, but segfaults if you try to use 'data'
// because 'n' contains garabge at this point.
Test2D::Test2D(const int sizeX, const int sizeY) : data(n, boost::extents[sizeX][sizeY]) // <<-- fail
{
xSize = sizeX;
ySize = sizeY;
// In the actual application, n will be populated by data arriving
// on TCP stream. The header on those mesasges contain total
// contiguous buffer size and X,Y dimensions, followed by the data.
n = (int*)malloc(xSize * ySize * sizeof(int));
// I want to set the multi_array_ref origin and define extents right
// here. The thought was to set the origin to 'n', and then
// resize(), but how? Of course I can't actually construct it here
// as shown. Seems like there should be a simple way to set
// (change) the origin pointer. There probably is in fact. But I
// can't seem to figure it out.
data(n, boost::extents[xSize][ySize]);
}
【问题讨论】:
-
严格回答标题问题:您不能重新初始化
multi_array_ref(句号)。如果您想要这种行为,请使用间接。
标签: c++ multidimensional-array boost