是std :: cout保证被初始化吗? [英] Is std::cout guaranteed to be initialized?

查看:143
本文介绍了是std :: cout保证被初始化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C ++的了解是,不应假设全局实例的构造(和破坏)的顺序。

What I know about C++ is that the order of the constructions (and destructions) of global instances should not be assumed.

全局实例,其在构造函​​数< $ c>中使用 std :: cout 析构函数,我有一个问题。

While I'm writing code with a global instance which uses std::cout in the constructor & destructor, I got a question.

std :: cout 也是iostream的全局实例。 std :: cout 保证在任何其他全局实例之前初始化?

std::cout is also a global instance of iostream. Is std::cout guaranteed to be initialized before any other global instances?

我写了一个简单的测试代码,它工作正常,但仍然不知道为什么。

I wrote a simple test code and it works perfectly, but still I don't know why.

#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;
}

打印

test::ctor
Hello world
test::dtor

代码是否有可能不按预期运行?

Is there any possibility that the code doesn't run as expected?

推荐答案

如果你使用C ++ 03或C ++ 11。

The answer differs depending on if you're using C++03 or C++11.

在C ++ 11中,你的代码可以工作,但在C ++ 03它未指定;你唯一的保证是,在输入 main()的时候,标准流已经被初始化。 (这就是说,所有主流实现在运行任何动态初始化之前初始化它们,使它们很好使用。)

In C++11, your code is guaranteed to work, but in C++03 it's unspecified; your only guarantee is that by the time main() is entered, the standard streams had been initialized. (That said, all mainstream implementations initialize them prior to running any dynamic initialization, making them fine to use.)

你可以通过构造一个 std :: ios_base :: Init 对象,如下所示:

You can force initialization by constructing an std::ios_base::Init object, like so:

#include <iostream>

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

private:
    std::ios_base::Init mInitializer;
};

test t;

int main()
{
    std::cout << "Hello world" << std::endl;
    return 0;
}



现在当 test 结构,它初始化 mInitializer 并保证流可以使用。

Now when test constructs, it initializes mInitializer and guarantees the streams are ready to use.

C ++ 11修复这个稍微恼人 #include< iostream> 其中 static std :: ios_base :: Init __unspecified_name __; 。这将自动保证流可以使用。

C++11 fixed this slightly annoying behavior by acting as if every instance of #include <iostream> where followed by static std::ios_base::Init __unspecified_name__;. This automatically guarantees the streams are ready to use.

这篇关于是std :: cout保证被初始化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆