Note that there are some explanatory texts on larger screens.

plurals
  1. POCallling object constructor/destructor with a custom allocator
    primarykey
    data
    text
    <p>I have been looking into custom allocators and I quite often see them using some kind of function to allocate memory. For testing purposes and further educate my self, I tried to make a "simple" example of doing so. However, there is one fundamental thing I am understand on how to do. One of the key differences in <code>malloc</code> vs <code>new</code> is that with new the constructor is called. What if I wanted to write my own allocator that was essentially replacing <code>new</code>, how would I get the constructor to be called when using <code>malloc</code>?</p> <p>I understand that on classes I can overload <code>new</code> and <code>delete</code> for the class, so I suppose a big part of the question is, how is <code>new</code> calling the objects constructor during allocation? Similarly, I am interested in how <code>delete</code> is calling the destructor. </p> <p>I created a sample test code that I was hoping to have the <code>SomeClass</code> constructor called during allocation, but I don't see how.</p> <pre><code>#include &lt;malloc.h&gt; void* SomeAllocationFunction(size_t size) { return malloc(size); } class SomeClass { public: SomeClass() { int con = 1000; } ~SomeClass() { int des = 80; } }; int main(void){ SomeClass* t = (SomeClass*)SomeAllocationFunction(sizeof(SomeClass)); return 0; } </code></pre> <p>(As a note, I know I can just use <code>new</code>. However, for the purposes of learning I am trying to create a custom allocator that does not just call <code>new</code> or <code>placement new</code>).</p>
    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.
    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