gpt4 book ai didi

c++ - std::cout 是否保证被初始化?

转载 作者:IT老高 更新时间:2023-10-28 12:31:00 33 4
gpt4 key购买 nike

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

当我使用在构造函数和析构函数中使用 std::cout 的全局实例编写代码时,我遇到了一个问题。

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

我写了一个简单的测试代码,它运行良好,但我仍然不知道为什么。

#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

有没有可能代码没有按预期运行?

最佳答案

答案会有所不同,具体取决于您使用的是 C++03 还是 C++11。

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

您可以通过构造 std::ios_base::Init 来强制初始化对象,像这样:

#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并保证流可以使用。

C++11 修复了这个有点烦人的行为,就像 #include <iostream> 的每个实例一样。紧随其后的是 static std::ios_base::Init __unspecified_name__; .这会自动保证流可以使用。

关于c++ - std::cout 是否保证被初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8784892/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com