Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Firstly, you are not allocating a "block of <code>T*</code>". You are allocating a "block of <code>T</code>".</p> <p>Secondly, if your <code>T</code> has non-trivial constructor, then until elements are constructed, your block is not really a "block of T", but rather a block of raw memory. There's no point in involving <code>T</code> here at all (except for calculating size). A <code>void *</code> pointer is more appropriate with raw memory. </p> <p>To allocate the memory you can use whatever you prefer</p> <pre><code>void *raw_data = malloc(num * sizeof(T)); </code></pre> <p>or</p> <pre><code>void *raw_data = new unsigned char[num * sizeof(T)]; </code></pre> <p>or</p> <pre><code>void *raw_data = ::operator new(num * sizeof(T)); </code></pre> <p>or</p> <pre><code>std::allocator&lt;T&gt; a; void *raw_data = a.allocate(num); // or // T *raw_data = a.allocate(num); </code></pre> <p>Later, when you actually construct the elements (using placement new, as you said), you'll finally get a meaningful pointer of type <code>T *</code>, but as long as the memory is raw, using <code>T *</code> makes little sense (although it is not an error).</p> <p>Unless your <code>T</code> has some exotic alignment requirements, the memory returned by the above allocation functions will be properly aligned.</p> <p>You might actually want to take a look at the memory utilities provided by C++ standard library: <code>std::allocator&lt;&gt;</code> with <code>allocate</code> and <code>construct</code> methods, and algorithms as <code>uninitialized_fill</code> etc. instead or trying to reinvent the wheel.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload