Is std::cout fully operating on the stack?
Asked Answered
C

2

7

In C++, when I am using std::cout like that:

std::cout << "myString" << std::endl;

Is there anything that will be allocated on the heap by std::cout? Or will std::cout do everything on the stack (meaning that std::cout and its underlying functions won't do any new/malloc/etc...)?

I want to know if heavily using std::cout could cause some heap fragmentation

Cheder answered 23/4, 2012 at 17:41 Comment(4)
There is no guarantee that operator<<(std::ostream&, T) won't invoke new. This is obviously true for any user-defined T.Ramp
Why are you worried by heap fragmentation. Is there something else you are doing that makes this a big concern?Skeet
@LokiAstari I am just asking that out of curiosity.Cheder
Even more fundamentally, the standard doesn't talk about stack versus heap. It's entirely possible for a C++ implementation to not have a stack, by dynamically allocating everything.Bump
P
7

In this specific example your code isn't causing any direct allocations on the heap. However it's possible for the implementation of any method to use the heap for part of it's work. This is perfectly fine so long as the method implementation properly cleans up after itself.

This logic applies to methods such as operator<<(std::ostream&, T).

Philologian answered 23/4, 2012 at 17:44 Comment(2)
So it depends on the implementation of the stl. Isn't there anything that specifies how the memory should be handled by std::cout in the stl?Cheder
@olchauvin it depends on the implementation of stl and the implementation of operator<< for a given T. I don't believe there is any specification available for how the implementation of cout manages memory.Philologian
S
5

This completely depends on a certain implementation of the basic C++ libraries

Seaweed answered 23/4, 2012 at 17:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.