C++: Difference between revisions

Jump to navigation Jump to search
72 bytes added ,  26 days ago
m
Bot: Replace deprecated source tag with syntaxhighlight
[unchecked revision][unchecked revision]
m (Bot: Replace deprecated source tag with syntaxhighlight)
m (Bot: Replace deprecated source tag with syntaxhighlight)
 
Line 254:
Below you will find some example code. Simply call '''runInit()''' if you want to initialize any static objects and then call '''runTerm()''' if static object destructors are to be run.
 
<sourcesyntaxhighlight lang="cpp">
typedef void (*_PVFV)(void);
typedef int (*_PIFV)(void);
Line 348:
__declspec(allocate(".CRT$XIB")) static _PIFV pinit = onexitinit;
#pragma data_seg()
</syntaxhighlight>
</source>
 
== Local Static Variables (GCC Only) ==
Line 386:
The actual code emitted by GCC to call a local static variable's constructor looks something like this:
 
<sourcesyntaxhighlight lang="cpp">
static <type> guard;
 
Line 413:
}
}
</syntaxhighlight>
</source>
 
== The Operators 'new' and 'delete' ==
Line 420:
Every time you call one of the operators '''new''', '''new[]''', '''delete''', or '''delete[]''', the compiler inserts a call to them. The most simple implementation would be to map them to your kernel's '''malloc''' and '''free'''. For example:
 
<sourcesyntaxhighlight lang="cpp">
#include <stddef.h>
 
Line 442:
free(p);
}
</syntaxhighlight>
</source>
 
You could also let '''new''' use '''calloc''' (allocate and zero). This way, newly allocated memory will always be zeroed (thus, not contain garbage). The standard '''new''' implementations do however not clear the returned memory.
Line 451:
In C++ (especially in OS code where structures can be found at fixed addresses) it can be useful to construct an object in memory obtained elsewhere. This is accomplished through a technique known as 'placement new'. For example, say you wanted to create an APIC object at address '''0x09FFF0000''', then this snippet of code will use placement new to do the trick:
 
<sourcesyntaxhighlight lang="cpp">
void *apic_address = reinterpret_cast<void *>(0x09FFF0000);
APIC *apic = new (apic_address) APIC;
</syntaxhighlight>
</source>
 
In order to use placement new, you need special overloads of the new and delete operators defined in scope. Fortunately, the required definitions are simple and can be inlined in a header file (the C++ standard puts them in a header called '''new''').
Cookies help us deliver our services. By using our services, you agree to our use of cookies.

Navigation menu