Boost Asio 示例 - 奇怪的 C++句法
我刚刚查看了 boost asio 框架和示例。在 Daytime.3 - 异步的源代码中TCP 日间服务器,代码为 tcp_server 类定义了一个构造函数,如下所示:
tcp_server(boost::asio::io_service& io_service) : acceptor_(io_service, tcp::endpoint(tcp::v4(), 50500))
我很困惑构造函数如何初始化 acceptor_ 实例变量稍后在私有部分中定义?我想在构造函数体内编写等效的初始化代码(仅供学习),但我无法弄清楚这个 ivar 是如何初始化的。
非常感谢您的帮助。
I've just been having a look at the boost asio framework and the examples. In the source code for Daytime.3 - An asynchronous TCP daytime server, the code defines a constructor for the tcp_server class as follows:
tcp_server(boost::asio::io_service& io_service) : acceptor_(io_service, tcp::endpoint(tcp::v4(), 50500))
I'm confused as to how the constructor is initializing the acceptor_ instance variable which is defined later on in the private section? I wanted to write equivalent code for this initialization within the body of the constructor (just for learning), but I can't figure out how this ivar is being initialized.
Many thanks in advance for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯..为什么它不能这样做呢?成员变量在整个类中都是可见的,无论它们在哪里定义:
如果您的意思是在冒号
:
之后初始化时如何工作,请搜索“初始化程序列表”/“构造函数初始化程序” “如果你想要标准的措辞。编辑:考虑这个类:
现在考虑这个函数和其他类:
您可以根据需要初始化初始化列表中的成员,假设该成员具有合适的构造函数。现在,对于
const
成员,您只能以这种方式初始化它们,因为在构造函数体内,它不能再被分配。您只能使用非常量和非引用变量来做到这一点:如果这没有任何帮助,我想您确实没有表达您不理解的内容。
Uhm.. why shouldn't it be able to do so? The member variables are visible through-out the whole class, no matter where they are defined:
If you meant how that while initialization thing works after the colon
:
, search for "initializer list"/"ctor initializer" if you want the standard wording.Edit: Consider this class:
And now consider this function and other class:
You can initialize a member in the initializer list however you want, assuming the member has a fitting constructor. Now, for
const
member, you can only initialize them that way, because inside the ctor body, it can't be assigned any more. You could only do that with non-const and non-reference variables:If this isn't any help, I guess you really don't express what you don't understand.