basav
basav

Reputation: 1495

Stl c++ dynamic memory allocation

I came across some legacy code and I see this.

typedef std::queue < EventDataPair > EventQueue;
_eventQueue = new EventQueue();

Why would one want to use a stl Queue allocated on Heap??? The class containing this code is a Singleton.

To Generalise it, When should one allocate a stl on Heap??? STL's themselves are dynamic in nature, and they may use heap internally.

Furthermore, won't you have the overhead of deallocating it in the destructor??

Upvotes: 0

Views: 887

Answers (2)

opetroch
opetroch

Reputation: 4095

One reason I can think of, is to avoid overhead of creating a copy when returning it from a function.

However, this is not needed any more with C++ 11 and move semantics.

Have a look at this example that Bjarne Stroustrap is talking about.

Upvotes: 1

Šimon T&#243;th
Šimon T&#243;th

Reputation: 36423

Well, unless you want to share the particular object between different contexts in the code there isn't much incentive to allocate on heap.

However for some legacy architectures you might be concerned with the size of your stack.

Upvotes: 2

Related Questions