You have a misunderstanding about how types work in C++. Every type has a fixed size. You can get this size with sizeof
. For example, on a typical platform, a vector<Test*>
has a size of 24 bytes.
When you allocate a vector on the stack, you are only allocating those 24 bytes on the stack. When you add objects to the vector, the vector will allocate memory from the heap to store those objects.
like I said I have to stick with this implementation since it save more stack memory than storing vector on the stack.
It won't. So you don't have to stick with this implementation. Switch to a sensible one such as std::vector<std::unique_ptr<Test>>
.
And I dont want objects to be copied or moved to prevent moving objects and keeping hollow ones that take more space
A sensible implementation (such as std::vector<std::unique_ptr<Test>>
) won't move the underlying objects. Move semantics for std::vector
are already optimal on any sensible platform.
You are expecting moving a std::unique_ptr
to be significantly different from moving a std::vector
. Your reasoning for that assumption is faulty and, even if it was correct, this would still be a pointless increase in complexity.
In fact, why not just use vector<Test>
?
Check this out:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> a;
for (int i = 0; i < 10; ++i)
a.push_back(i);
std::cout << &a[0] << std::endl;
std::vector<int> b = std::move(a);
std::cout << &b[0] << std::endl;
}
Output:
0x563caf0f1f20
0x563caf0f1f20
Notice that moving the vector didn't even move the objects in the vector. It just transferred ownership of the objects from one vector to the other.
Stop trying to optimize things that are already optimized.