C++ 可以在构造函数初始值设定项列表中调用函数吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4162021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it ok to call a function in constructor initializer list?
提问by nakiya
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?
或者我应该更改构造函数并Logger* const
从构造的位置传递一个PluginLoader
?
回答by GManNickG
That's perfectly fine and normal. p_Builder
was initialized before it.
这是完全正常的。p_Builder
在它之前被初始化。
回答by Benjamin Lindley
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. 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.
请注意,我对您的代码进行了 2 处更改。首先,在类定义中,我在 p_Builder 之前声明了 p_Logger。其次,我使用成员 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.
请始终记住,成员按照它们在类定义中出现的顺序进行初始化。你把它们放在初始化列表中的顺序是无关紧要的。
回答by Jason Rogers
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 函数中,仅出于灵活性目的:如果您以后必须创建其他构造函数。