c++ - Can I overload 'operator new' with a different return type? -
here's situation: want overload "operator new" instead of allocating object in random space in memory, gets allocated in pre-defined memory buffer. want able save buffer file , load in future, want use handles instead of pointers. want, ideally, "operator new" return handle can use go straight object's place in it's buffer. possible in c++(11)? if not, best alternatives?
afaik cannot change return type of new
operator. scenario try following approach:
define
handle
(orhandle<t>
, if need handles more 1 type) class, internally stores index allocation area (i.e.handle
has 1 single member variableindex
).handle
class need internally somehow have access allocation subsystem, i.e. need know actual storage area (buffer) located.define constructor
handle
taking pointer (returnednew
implementation) argument , computing index (e.g. subtracting beginning of storage area)also define dereferencing operator (
operator *
)handle
class returning reference "handled" object (e.g. adding index beginning of storage area...)in code, alsways use
handle<t>
instead of pointerst
, @ least @ every point store handle/pointer.
that way, when serialize/deserialize storage area, indices written disk. using handle
class same using pointers. computation of actual pointers done internally.
of course have performance penalty, since instead of directly using pointers there computation. might affect optimization can done compiler. 1 idea minimize performance issue implement conversion operator handle<t>
t*
, code pieces use single handle/pointer lot "precompute" pointer , use throughout code.
Comments
Post a Comment