1

たとえば、200 個の整数の配列があります。私がしたいのは、それを 80 個の整数の 2 つの配列に変換し、間にある 40 個の整数を削除することです。もちろん、目標は、長さ80の整数の2つの新しい配列を割り当てて最初の配列からコピーすることなく、既存のメモリブロックを使用することです.

移動セマンティクスは、同様の低レベルのアプローチを使用して右辺値の不要なコピーを回避するため、同様の効果を達成するが既存のデータを複数のオブジェクトに割り当てる低レベルのアプローチがあるかどうかが私の質問です。

たとえば、カットがあり、新しい要素が始まる生のメモリアドレスにポインターを割り当て、同じデータを使用する配列として機能させ、初期配列によって既に割り当てられて埋められているか?

当然、初期配列を削除してそのアドレスを取得し、それを使用してそのメモリ領域を新しい要素に割り当てることもできますが、新しいオブジェクトを割り当てる正確なアドレスを C++ に伝えることは可能ですか? また、初期配列のデータが削除されてから、同じメモリ領域が新しいオブジェクトに再割り当てされるまでの間に破損しないことを保証する方法はありますか?

このようなアプローチは、私が読んだ c++ に関するどの本にもありませんが、目的の結果を達成するための低レベルのトリックが存在する可能性が非常に高いと感じています。

4

4 に答える 4

2

私が単純に行うことは、関連するスライスへのポインターを渡すことです。

void i_need_80(int arr[80]);  // same as "int*"

std::array<int, 200> the_array;

i_need_80(the_array);
i_need_80(the_array + 120);

の代わりにstd::array<int, 200>ダイナミック を使用することもできます。std::vector<int> vその場合はv.data()and としv.data() + 120ます。

使用しないでくださいnew

于 2011-11-29T13:39:21.097 に答える
2

Yes, this is possible using placement-new. However, there is no way to guarantee that the content of a memory-location will not be changed between delete and a reallocation. Anyway, placement-new only enables you to construct an object in memory that you already own. So you'd have to allocate a pool of memory and then do your own memory management inside that pool.

于 2011-11-29T13:29:39.613 に答える
2

You can use placement new but it's generally not a good idea to go this low-level, unless you are really constrained.

Using it is a good idea when:

  • You implement a memory pool
  • You need to write to a precise memory location because the platform requires that (for example, memory mapped I/O on some embedded device).

Disadvantages of using it:

  • You need to make sure that the allocated memory is large enough to hold the object.
  • You need to explicitly call the destructor when the object is not needed anymore.

is there a way to guarantee the data of the initial array wont be corrupted in between its deletion and the reallocation of that same memory area to a new object

No, that's up to the OS. It might be possible with a platform-specific API if it exists.

于 2011-11-29T13:30:50.437 に答える
0

唯一できることは、realloc() を呼び出して、realloc() の malloc() で割り当てられたブロックのサイズを変更 (および場合によっては移動) することです。ブロックが new[] を使用して割り当てられた場合でも、それは不可能です。必要なものには、メモリ管理関数 malloc()、free()、および realloc() の書き直し (再発明) が必要です。

于 2011-11-29T13:32:36.483 に答える