+ 2
Why vector does not call heap allocation
Hi https://www.sololearn.com/compiler-playground/cqFgWopfA64b Why heap allocation is not happening on this code? I have created one object into vector and thought that allocation is on heap for class object. Why so? Am I missing something?
12 Antworten
+ 2
This is because you haven't passed any custom allocator to your vector and default allocator uses global "new" and "delete" operators to allocate your memory.
See this:
https://code.sololearn.com/cKZJC4JPo9Z2/?ref=app
+ 3
Ketan Lalcheta something to do with new?
I never dig this deep, just how to properly use something is enough for me.😁
https://www.daniweb.com/programming/software-development/threads/382895/stl-vector-and-malloc
+ 2
KrOW and Bob_Li , i am also not having dare to do allocation customely 😝😝
I am just trying to observe heap allocation and de allocation in normal scenario of vector. Studying this as one of my task is to identify performance lag and i feel that issue is frequent allocation on heap... i might be wrong also but thats why trying to understand this in details.
+ 1
Ketan Lalcheta new operator overload is called when you create an object with "new" (really??? 😁) but in your code you creating the object without new (then onto stack)... Thats all
+ 1
KrOW but vector elements are called on heap... right ? Vector itself is on stack but its container for elements is on heap... Right ?
+ 1
Ketan Lalcheta from my meager understanding, you are basically correct
https://stackoverflow.com/questions/8036474/when-vectors-are-allocated-do-they-use-memory-on-the-heap-or-the-stack
but you can change the behavior by writing your own custom allocator.
Just thinking about having the need to do optimizations like these is numbing my mind.. you might as well program it in assembly language.😂
+ 1
Ketan Lalcheta Yes, the vector items are created on the heap.
Vector object (eg. the direct internal data) is allocated onto stack but some data refer to data onto heap... Just for make all simple:
int* a= new int;
"a" pointer is onto stack but it refers to data onto heap.
+ 1
Bob_Li Yes, custom allocator is not for every day use but for optimizing some scenarios... A good reading is here https://indiegamedev.net/2022/03/27/custom-c20-memory-allocators-for-stl-containers/
+ 1
KrOW 😵😵
optimization is a deep dark rabbit hole. Not for the weak-hearted ....
General knowledge is good enough for me.😅
Ketan Lalcheta, good luck on your quest for the dark magic...😱
+ 1
The global new operator is called by library triggered by vector internal allocation not by vector construction (thats is always did onto stack so the temp testtt object passed as parameter)... Just to be clear.
Anyway dont overload new/delete globally if you dont know what it do
+ 1
Thanks Arsenic for solving my doubt
0
😂