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

一曲冷凌霜 提交于 2019-11-29 01:38:06

问题


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?


回答1:


That's perfectly fine and normal. p_Builder was initialized before it.




回答2:


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)

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. 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.




回答3:


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.



来源:https://stackoverflow.com/questions/4162021/is-it-ok-to-call-a-function-in-constructor-initializer-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!