16 Haziran 2020 Salı

Streamler std::ios_base Sınıfı

Giriş
Kalıtım hiyerarşisi şöyle
std::ios_base <--std::basic_ios <--std::istream ve std::ostream
Init Alanı - Static Değişkendir
std::cout,std::cerr gibi nesneleri ilklendirir. Çalışma şekli şöyledir.

<iostream> cpp dosyasına dahil edilince şu static değişken de cpp'ye dahil edilir.
static ios_base::Init __ioinit;
Açıklaması şöyle.
Including the iostream header has the effect of adding the definition of a static std::ios_base::Init object. The constructor of this static object initializes the standard stream objects std::cout, std::cerr and so forth.

The reason it's done is to avoid the static initialization order fiasco. It ensures the stream objects are properly initialized across translation units.
Açıklaması şöyle.
This object is used to initialize the standard streams (std::cout and its friends). This method is called Schwarz Counter and it ensures that the standard streams are always initialized before their first use (provided iostream header has been included).

That function _GLOBAL__sub_I_main is code the compiler generates for each translation unit that calls the constructors of global objects in that translation unit and also arranges for the corresponding destructor calls to be invoked at exit. This code is invoked by the C++ standard library start-up code before main is called.
Örnek
Global nesnelerin ilklendirilmesini anlamak için elimizde şöyle bir kod olsun.
#include <iostream>

struct test
{
  test() { std::cout << "test::ctor" << std::endl; }
  ~test() { std::cout << "test::dtor" << std::endl; }
};

test t;

int main()
{
    std::cout << "Hello world" << std::endl;
    return 0;
}
C++11 ile yukarıdaki örneği şu çıktıyı vermesi garanti edilir.
test::ctor
Hello world
test::dtor
sync_with_stdio metodu
C ve C++ kütüphaneleri I/O için karıştırılarak kullanılabilir. C++ I/O kütüphanesi altta her zaman C ile senkronize olmaya çalışan bir kod çalıştırır. Ancak sadece C++ kullandığımızı biliyorsak ve hız önemliyse bu senkronizasyon kapatılabilir.

Yani "cout <<" printf ile senkronize olmaya çalışmadığı için bu şekilde hızlandırılabilir.

Bu çağrı main metodunun başında herhangi bir I/O işlemi yapılmadan gerçekleşmeli. Açıklaması şöyle.
If this function is called after I/O has occurred on the standard stream, the behavior is implementation-defined
Örnek
Şöyle yaparız
int main(){
  ios_base::sync_with_stdio(0);
  ...
}    
Örnek
Şöyle yaparız.
std::ios_base::sync_with_stdio(false); // turn off synchronization with the C


Hiç yorum yok:

Yorum Gönder