Note that there are some explanatory texts on larger screens.

plurals
  1. POoverloading new/delete problem
    primarykey
    data
    text
    <p>This is my scenario, Im trying to overload new and delete globally. I have written my allocator class in a file called allocator.h. And what I am trying to achieve is that if a file is including this header file, my version of new and delete should be used.</p> <p>So in a header file "allocator.h" i have declared the two functions </p> <pre><code>extern void* operator new(std::size_t size); extern void operator delete(void *p, std::size_t size); </code></pre> <p>I the same header file I have a class that does all the allocator stuff,</p> <pre><code>class SmallObjAllocator { ... }; </code></pre> <p>I want to call this class from the new and delete functions and I would like the class to be static, so I have done this:</p> <pre><code>template&lt;unsigned dummy&gt; struct My_SmallObjectAllocatorImpl { static SmallObjAllocator myAlloc; }; template&lt;unsigned dummy&gt; SmallObjAllocator My_SmallObjectAllocatorImpl&lt;dummy&gt;::myAlloc(DEFAULT_CHUNK_SIZE, MAX_OBJ_SIZE); typedef My_SmallObjectAllocatorImpl&lt;0&gt; My_SmallObjectAllocator; </code></pre> <p>and in the cpp file it looks like this: allocator.cc</p> <pre><code>void* operator new(std::size_t size) { std::cout &lt;&lt; "using my new" &lt;&lt; std::endl; if(size &gt; MAX_OBJ_SIZE) return malloc(size); else return My_SmallObjectAllocator::myAlloc.allocate(size); } void operator delete(void *p, std::size_t size) { if(size &gt; MAX_OBJ_SIZE) free(p); else My_SmallObjectAllocator::myAlloc.deallocate(p, size); } </code></pre> <p>The problem is when I try to call the constructor for the class SmallObjAllocator which is a static object. For some reason the compiler are calling my overloaded function new when initializing it. So it then tries to use My_SmallObjectAllocator::myAlloc.deallocate(p, size); which is not defined so the program crashes.</p> <p>So why are the compiler calling new when I define a static object? and how can I solve it?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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