This sample replaces functions like nlib_malloc
and nlib_free
with implementations using nmalloc
and nfree
. It replaces new
and delete
This samples operations can be accomplished more easily by defining the macro NLIB_REPLACE_MALLOC_NEW
in NMalloc.h
.
#include <new>
#include <vector>
#if 1
extern "C" {
}
}
}
}
#ifndef NN_PLATFORM_CTR
void*
operator new(
size_t size) {
return nlib_malloc(size); }
void*
operator new[](
size_t size) {
return nlib_malloc(size); }
void
}
void operator delete(
void* ptr,
size_t size,
const std::nothrow_t&)
NLIB_NOEXCEPT {
}
void operator delete[](
void* ptr,
size_t size,
const std::nothrow_t&)
NLIB_NOEXCEPT {
}
#else
void*
operator new(
size_t size)
throw(std::bad_alloc) {
return nlib_malloc(size); }
void operator delete(
void* ptr)
throw() {
nlib_free(ptr); }
void*
operator new(
size_t size,
const std::nothrow_t&)
throw() {
return nlib_malloc(size); }
void*
operator new[](
size_t size)
throw(std::bad_alloc) {
return nlib_malloc(size); }
void operator delete[](
void* ptr)
throw() {
nlib_free(ptr); }
void*
operator new[](
size_t size,
const std::nothrow_t&)
throw() {
return nlib_malloc(size); }
#endif
#else
#endif
typedef std::vector<int> MyVec;
static bool VectorPushback() {
MyVec vec;
for (int i = 0; i < 10000; ++i) {
vec.push_back(i);
if (i == 5000) {
}
}
for (int i = 0; i < 10000; ++i) {
if (vec[i] != i) return false;
}
vec.clear();
MyVec(vec).swap(vec);
return true;
}
static bool VectorPushbackWithReserve() {
MyVec vec;
vec.reserve(10000);
for (int i = 0; i < 10000; ++i) {
vec.push_back(i);
}
for (int i = 0; i < 10000; ++i) {
if (vec[i] != i) return false;
}
nlib_printf(
"#\n# heap status: i == 10000(with reserve)\n#\n");
return true;
}
#ifdef NLIB_HAS_VIRTUALMEMORY
settings->
size = 1024 * 512;
}
#else
const size_t heapmem_size = 1024 * 512;
settings->
addr = heapmem;
settings->
size = heapmem_size;
}
#endif
static bool SampleMain(int, char**) {
return VectorPushback() && VectorPushbackWithReserve();
}
NLIB_MAINFUNC