Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

c++ - STL containers on the stack and the heap

If std::vector and friends are self resizing, does that mean if I declare a vector like so:

std::vector<string> myvec;

Then it'll resize using more stack, whereas:

std::vector<string> *myvec = new std::vector<string>();

Would resize using more heap?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Vectors allocate on the heap in their internals.

The only thing you pay for in the stack for a stack based bector is a couple of bytes, the inner buffer will always be allocated from the heap.

So effectively when you do a vec = new vector() you are allocating a small quantity, which may not be really good.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...