c++ link temporary allocations in function to custom allocator?
I am currently working on some simple custom allocators in c++ which generally works allready. I also overloaded the new/delete operators to allocate memory from my own allocator. Anyways I came across some scenarios where I don't really know where the memory comes from like this:
void myFunc(){
开发者_运维知识库 myObj testObj();
....do something with it
}
In this case testObj would only be valid inside the function, but where would its memory come from? Is there anyway I could link it to my allocator? Would I have to create to object using new and delete or is there another way?
Thanks
(myObj testObj();
declares a function named testObj
which returns a myObj
. Use myObj testObj;
instead.)
The memory comes from the stack. It will be auto
-matically destroyed when leaving the scope.
To use your new
and delete
you must of course call new
and delete
:
myObj* p_testObj = new myObj;
...
delete p_testObj;
But allocation on stack is the most efficient since it just involves 1 instruction sub esp, ??
. I don't see a reason to use custom allocation unless myObj
is huge.
精彩评论