[英]What method do you use to initialize member variables?
Suppose I have a class Foo
, with a member variable that is a std::vector
of floats, bar
. 假设我有一个Foo
类,其成员变量是floats, bar
的std::vector
。 I then create an instance of Foo
, called foo
. 然后,我创建一个名为foo
的Foo
实例。 Let's say that I do not know the length of bar
before the program runs, but at the point when foo
's constructor is called, I know that it's length should be x
. 假设我在程序运行之前不知道bar
的长度,但是在调用foo
的构造函数时,我知道它的长度应该为x
。
There are three ways I can think of to initialize the length of bar
, and I'm just wondering which of the three most people tend to use. 我可以考虑三种方法来初始化bar
的长度,而我只是想知道大多数人倾向于使用三种方法中的哪一种。 I have ranked them in order of what I would consider to be "best practice", but I'm more curious about what method people "actually" use in practice. 我已经按照我认为是“最佳实践”的顺序对其进行了排名,但是我对人们在实践中“实际”使用哪种方法感到更加好奇。 Sometimes I use methods which make the code clearer to follow, rather than necessarily following best practice... 有时我使用一些使代码更易于遵循的方法,而不必遵循最佳实践。
bar
is a private member, and I resize it during foo's
constructor, eg Foo foo(x){bar.resize(x)};
bar
是私有成员,我在foo's
构造函数中调整其大小,例如Foo foo(x){bar.resize(x)};
bar
is a private member, and I call foo.ResizeBar(x)
which resizes bar
internally, after creating foo
. bar
是私有成员,在创建foo
之后,我调用foo.ResizeBar(x)
在内部调整bar
大小。
bar
is a public member, and I call foo.bar.resize(x)
, after creating foo
. bar
是公共成员,在创建foo
之后,我调用foo.bar.resize(x)
。
Or, in code: 或者,在代码中:
1. 1。
class Foo
{
private:
std::vector<float> bar;
public:
Foo(int x)
{
bar.resize(x);
};
};
int main()
{
Foo foo(100);
return 0;
}
2. 2。
class Foo
{
private:
std::vector<float> bar;
public:
Foo()
{
};
void ResizeBar(int x)
{
bar.resize(x);
};
};
int main()
{
Foo foo;
foo.ResizeBar(100);
return 0;
}
3. 3。
class Foo
{
public:
std::vector<float> bar;
Foo()
{
};
};
int main()
{
Foo foo;
foo.bar.resize(100);
return 0;
}
The problem with all three of your methods is that you're needlessly invoking the default initializer for your vector, and then modifying the already initialized vector to suit your needs. 这三种方法的问题在于,您不必要地为向量调用默认的初始化程序, 然后修改已初始化的向量以满足您的需要。
You should be invoking the correct initializer using the initializer list: 您应该使用初始化器列表调用正确的初始化器:
Foo::Foo(std::size_t x) : bar(x, 0) { }
The best method is not in the list of options you posted. 最好的方法不在您发布的选项列表中。 The best method is to initialize bar
using member initializer lists . 最好的方法是使用成员初始化程序列表初始化bar
。
Foo::Foo(int x) : bar(x) {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.