简体   繁体   中英

When memory gets allocated to predefined stream objects?

Before you start to mark this question as duplicate I've already this but it doesn't answer my question.

stream objects like std::cout , std::cin are global instances of ostream & istream classes. But my question is when memory is allocated to these objects? When these objects are initialized? Is memory allocated at compile time or runtime or C++ runtime initialize these objects at runtime before calling main()? Where std::cout & std::cin object resides: in the stack, heap or data segment?

The stream objects are global variables, so they will reside in the global data segment. They might also internally allocate other memory for buffers, or whatever they need.

They are initialized, by some unspecified magic (= possibly implementation specific tricks), as early as possible, but no later than before the first statement of main.

when memory is allocated to these objects?

At the same time as to other global objects with static storage duration

When these objects are initialized?

When other static objects are intitialized, but before you will have chance to use them due to standard mandate and library tricks.

Where std::cout & std::cin object resides: in the stack, heap or data segment?

They reside in static memory . Strictly speaking there is no stack or heap in C++, only static, dynamic and automatic memory. Exact place would be dependend on library implementation.

These objects are guaranteed to be initialized during or before the first time an object of type std::ios_base::Init is constructed and are available for use in the constructors and destructors of static objects.

This is LLVM implementation: https://github.com/llvm-mirror/libcxx/blob/master/src/iostream.cpp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM