Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create an array while potentially using placement new
    primarykey
    data
    text
    <p>I have been working on creating a custom allocator as a fun exercise/practice and I ran into two potentials issues with creating arrays. For a typical call for allocation, I will use <code>malloc</code> and <code>placement new</code>. However, when I go to create an array I am confused on how it should be done. For once, I have noticed at some places that it seems <code>placement new</code> may not be safe for arrays such as <a href="https://stackoverflow.com/questions/4011577/placement-new-array-alignment">here</a>. I am also running into an error of my own while attempting to use <code>placement new</code> for an array. I will get the error of</p> <blockquote> <p>`error C2679: binary '=' : no operator found which takes a right-hand operand of type 'SomeClass *' (or there is no acceptable conversion)</p> </blockquote> <p>I understand the error (I believe) but I would prefer to have the error be solved via my array construction method. I have two questions</p> <p>1) How can an allocator create an array without using <code>new[]</code>? Is it with <code>placement new</code>? If so, what about the potential dangers mentioned from the link I posted above?</p> <p>2) If I am suppose to use <code>placement new</code> and call it on each one of the elements in the array, why am I getting the error mentioned above?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;new&gt; class SomeClass{ public: SomeClass() { printf("Constructed\n"); } ~SomeClass() { printf("Destructed\n"); } }; void* SomeAllocationFunction(size_t size) { return malloc(size); } template&lt;typename Type&gt; Type* SomeArrayAllocationFunction(size_t count){ Type* mem = (Type*)SomeAllocationFunction(sizeof(Type) * count); for(unsigned int i = 0; i &lt; count; ++i) { mem[i] = new(mem + i) Type(); } return mem; } int main(void){ SomeClass* t = SomeArrayAllocationFunction&lt;SomeClass&gt;(2); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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