Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding new with debug version without damaging placement new

Microsoft runtime library provides debug version of allocation functions. For C++ this is a debug variant of operator new with the signature:

void *operator new(size_t size, int blockType, const char *filename, int linenumber);

and a macro is defined like

#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)

Now to instrument all allocations, one normally defines

#if defined DEBUG_NEW
#define new DEBUG_NEW
#endif

However this definition breaks any place that uses placement new, because the two sets of arguments end up being syntax error. Now I can easily handle the few uses in our code, but the standard library and boost use placement new all over the place. So defining this globally means including a lot of stuff before the definition and that slows down compilation.

So would there be any way to instrument allocations in our code without pulling in headers just because they contain placement new and without having to either put the last define above in all files or writing DEBUG_NEW manually?

like image 457
Jan Hudec Avatar asked Oct 10 '12 08:10

Jan Hudec


People also ask

Does placement New allocate?

Placement new is a variation new operator in C++. Normal new operator does two things : (1) Allocates memory (2) Constructs an object in allocated memory. Placement new allows us to separate above two things. In placement new, we can pass a preallocated memory and construct an object in the passed memory.

In which cases we would need to use placement new?

Placement new allows you to construct an object in memory that's already allocated. You may want to do this for optimization when you need to construct multiple instances of an object, and it is faster not to re-allocate memory each time you need a new instance.

How to set BREAKPOINTS in visual studio code?

To set a breakpoint in source code: Click in the far left margin next to a line of code. You can also select the line and press F9, select Debug > Toggle Breakpoint, or right-click and select Breakpoint > Insert breakpoint. The breakpoint appears as a red dot in the left margin.


1 Answers

#pragma push_macro("new")
#undef new

new(pointer) my_class_t(arg1, arg2);

#pragma pop_macro("new")

or

#pragma push_macro("new")
#undef new

#include <...>
#include <...>
#include <...>

#pragma pop_macro("new")
like image 196
kaegoorn48 Avatar answered Sep 20 '22 22:09

kaegoorn48