考慮下面的代碼指點指點連續內存
struct foo
{
const int txt_len;
const int num_len;
char * txt;
int * num;
foo(int tl, int nl): txt_len(tl), num_len(nl)
{
char * tmp = new char[txt_len * sizeof(char) + num_len * sizeof(int)];
txt = new (tmp) char [txt_len * sizeof(char)];
num = new (tmp + txt_len * sizeof(char)) int[num_len * sizeof(int)];
// is this the same as above?
// txt = tmp;
// num = (int *) (tmp + txt_len * sizeof(char));
}
~foo()
{
delete[] txt; // is this the right way to free the memory?
}
};
我想*txt
和*num
是連續的,是最好的方式做到這一點?
放置新指針和指針算術是否有區別?我應該使用哪一個?
我不知道你可以在現有的內存上使用新的方式。爲你+1。 – rsaxvc 2012-01-07 04:27:36
如果不理解你爲什麼要連續記憶,很難給你一個有用的答案。這實際上取決於你打算如何處理它。 (例如,你是否打算取消引用它的指針?如果是這樣,什麼類型?你想要一個正常的結構將有間距?或者你想它打包?)上面的代碼是非法的,你不能通過安置新一個不對齊的指針。 – 2012-01-07 04:31:48
首先放置'int',因爲它具有更嚴格的對齊要求。並且'sizeof(char)'保證完全是'1'。 – 2012-01-07 04:37:17