gpt4 book ai didi

c++ - 为什么构造函数 Zlib_init 在 Bjarne Stroustrup 的书中的类 Zlib_init 中保持私有(private)

转载 作者:太空狗 更新时间:2023-10-29 19:59:32 25 4
gpt4 key购买 nike

在 Bjarne Stroustrup 的《The C++ Programming Language》一书中,作者说:

Sometimes when you design a library, it is necessary, or simply convenient, to invent a type with a constructor and a destructor with the sole purpose of initialization and cleanup. Such a type would be used once only: to allocate a static object so that the constructor and the destructor are called. For example:

 class  Zlib_init
{
Zlib_init() ; //get Zlib ready for use
~Zlib_init() ; //clean up after Zlib
};
Class Zlib
{
static Zlib_init x;
/ /...
};

Unfortunately, it is not guaranteed that such an object is initialized before its first use and destroyed after its last use in a program consisting of separately compiled units.

为什么作者将构造函数和析构函数保留为私有(private)成员?如果我们在由单独编译的单元组成的程序中使用它,为什么这种方法不起作用?调用构造函数Zlib_init()和析构函数~Zlib_init()不需要定义成员x吗?那么这个方法有什么用呢?它在本书的第 10.4.9 节中。

最佳答案

Why does the author keep the constructor and destructor as private members?

private 的构造函数和析构函数似乎是一个错字。
static 成员需要被定义,以便您可以使用它们。为了定义静态成员 x ,构造函数需要可访问。如果不是,链接器将提示 undefined reference 。

Online Sample :

class  Zlib_init 
{
Zlib_init() ; //get Zlib ready for use
~Zlib_init() ; //clean up after Zlib
public:
int j;
};
class Zlib
{
public:
static Zlib_init x;
};

Zlib_init Zlib::x;

int main()
{
Zlib::x.j = 10;

return 0;
}

输出:

prog.cpp:3: error: ‘Zlib_init::Zlib_init()’ is private     
prog.cpp:14: error: within this context
prog.cpp: In static member function ‘static void Zlib::__static_initialization_and_destruction_0(int, int)’:
prog.cpp:4: error: ‘Zlib_init::~Zlib_init()’ is private
prog.cpp:14: error: within this context

And why won't this method work if we use it in a program consisting of seperately compiled units?

如果你通过 making the constructor and destructor public 修正了上面提到的错字或者通过制作 Zlib a friend of class Zlib_init代码仍然面临另一个问题。
该问题在 C++ 中通常称为 Static Initialization Fiasco

好读:

[10.14] What's the "static initialization order fiasco"?
[10.17] How do I prevent the "static initialization order fiasco" for my static data members?

关于c++ - 为什么构造函数 Zlib_init 在 Bjarne Stroustrup 的书中的类 Zlib_init 中保持私有(private),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12739902/

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