简体   繁体   English

在构造函数初始化列表中调用函数是否可以?

[英]Is it ok to call a function in constructor initializer list?

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? 或者我应该更改构造函数并从构造PluginLoader位置传递Logger* const

That's perfectly fine and normal. 这完全正常和正常。 p_Builder was initialized before it. 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) 但是,我只是想提醒你注意不要这样做 :( GMan暗示这一点,我只是想说清楚)

class PluginLoader
{
   public:
      Logger* const p_Logger;   // p_Logger is listed first before p_Builder
      Builder* const p_Builder;

      //Others
};

PluginLoader::PluginLoader(Builder* const pBuilder)
   :p_Builder(pBuilder),
    p_Logger(p_Builder->GetLogger())   // Though listed 2nd, it is called first.
                                       // This wouldn't be a problem if pBuilder 
                                       // was used instead of p_Builder
{
   //Stuff
}

Note that I made 2 changes to your code. 请注意,我对您的代码进行了2次更改。 First, in the class definition, I declared p_Logger before p_Builder. 首先,在类定义中,我在p_Builder之前声明了p_Logger。 Second, I used the member p_Builder to initialize p_Logger, instead of the parameter. 其次,我使用成员p_Builder来初始化p_Logger,而不是参数。

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. 这些更改中的任何一个都可以,但是它们一起引入了一个错误,因为p_Logger首先被初始化,并且您使用未初始化的p_Builder来初始化它。

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. 你把它们放在初始化列表中的顺序是无关紧要的。

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. 而不是在构造函数中调用函数,将它们分组到init函数中,仅用于灵活性目的:如果以后必须创建其他构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM