可以调用成员初始值设定项列表中的函数吗?
我的直觉是不是。我处于以下情况:
class PluginLoader
{
public:
Builder* const p_Builder;
Logger* const p_Logger;
//Others
};
PluginLoader::PluginLoader(Builder* const pBuilder)
:p_Builder(pBuilder), p_Logger(pBuilder->GetLogger())
{
//Stuff
}
或者我应该更改构造函数并从构造 PluginLoader
的位置传递一个 Logger* const
?
My gut feeling is it is not. I am in the following situation:
class PluginLoader
{
public:
Builder* const p_Builder;
Logger* const p_Logger;
//Others
};
PluginLoader::PluginLoader(Builder* const pBuilder)
:p_Builder(pBuilder), p_Logger(pBuilder->GetLogger())
{
//Stuff
}
Or should I change the constructor and pass a Logger* const
from where PluginLoader
is constructed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是完全正常的。
p_Builder
在它之前被初始化。That's perfectly fine and normal.
p_Builder
was initialized before it.你拥有的很好。但是,我只是想警告您要小心不要这样做:(GMan 提到了这一点,我只是想让它完全清楚)
请注意,我对您的代码做了 2 处更改。首先,在类定义中,我在 p_Builder 之前声明了 p_Logger。其次,我使用成员 p_Builder 来初始化 p_Logger,而不是参数。
这些更改中的任何一个都可以,但是它们一起引入了一个错误,因为 p_Logger 首先被初始化,并且您使用未初始化的 p_Builder 来初始化它。
请始终记住,成员按照它们在类定义中出现的顺序进行初始化。并且将它们放入初始化列表中的顺序无关紧要。
What you have is fine. However, I just want to warn you to be careful not to do this: (GMan alluded to this, I just wanted to make it perfectly clear)
Note that I made 2 changes to your code. First, in the class definition, I declared p_Logger before p_Builder. Second, I used the member p_Builder to initialize p_Logger, instead of the parameter.
Either one of these changes would be fine, but together they introduce a bug, because p_Logger is initialized first, and you use the uninitialized p_Builder to initialize it.
Just always remember that the members are initialized in the order they appear in the class definition. And the order you put them in your initialization list is irrelevant.
非常好的实践。
我建议这样做(但纯粹是个人层面):
不要在构造函数中调用函数,而是将它们分组在 init 函数中,仅出于灵活性目的:如果您以后必须创建其他构造函数。
Perfectly good practice.
I would suggest this (but its on a purely personal level):
instead of having functions called in your constructor, to group them in a init function, only for flexibility purposes: if you later have to create other constructors.