gpt4 book ai didi

c++ - 关于 std::cout,为什么使用 "extern"而不是 "singleton pattern"

转载 作者:太空宇宙 更新时间:2023-11-04 12:34:16 25 4
gpt4 key购买 nike

我读了项目 04 提到的 effective C++

Avoid initialization order problems across translation units by re-placing non-local static objects with local static objects.

看了这篇文章后,我认为“全局且唯一的对象”应该是单例模式,而不是外部对象。

例如 I/O 对象(std::cout)

但 std::cout 似乎是外部对象。( http://www.cplusplus.com/reference/iostream/cout/ )

我对此很困惑。

编辑:添加代码

我从本书中获取了一些代码。

首先是糟糕的代码:

class FileSystem {
// from your library’s header file
public:
...std::size_t numDisks( ) const;
// one of many member functions...
};
extern FileSystem tfs;

the relative order of initialization of non-local staticobjects defined in different translation units is undefined.

所以当我调用 tfs 时,上述代码可能会出错。

因为tfs可能还没有完成初始化。

推荐代码:

class FileSystem { ... }; // as before
FileSystem& tfs()
{
static FileSystem fs;
return fs;
}
class Directory { ... };// as beforeDirectory::Directory( params )
Directory::Directory( params ) // as before, except references to tfs are
//now to tfs( )
{
...
std::size_t disks = tfs().numDisks( );
...
}
Directory& tempDir()
{
static Directory td(params);
return td;
}

最佳答案

使用 extern 变量允许(主观上)更好的语法

std::cout << stuff;

强调标准流是一个独特的对象,而不是某些函数调用的结果。由于流式传输旨在对流对象进行处理,因此使用对象表示法可以更好地融入其中。

至于静态初始化顺序的失败,标准库通过使用 Schwarz Counter 来避免它。初始化技术。初始化以明确定义的顺序进行,因为包含 iostream 会添加类型为 Init 的特殊全局对象。包括恩。对象的构造函数在首次使用之前处理流的初始化,无论首次使用是在何处。

关于c++ - 关于 std::cout,为什么使用 "extern"而不是 "singleton pattern",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57122982/

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