正确的方法来初始化向量成员变量 [英] Correct way to initialize vector member variable
本文介绍了正确的方法来初始化向量成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
//方法一
class ClassName
{
public:
ClassName():m_vecInts(){}
private:
std :: vector< int> m_vecInts
}
//方法二
className
{
public:
ClassName(){} // do nothing
private:
std :: vector< int> m_vecInts;
}
问题>初始化类的向量成员变量的正确方法是什么?
我们必须初始化它吗?
解决方案
请参阅http://en.cppreference.com/w/cpp/language/default_initialization
当具有自动存储持续时间的变量在没有初始化器的情况下声明时,默认初始化在三种情况下执行:
<当基类或非静态数据时,具有动态存储持续时间的对象由未包含初始化程序的新表达式创建
默认初始化的效果是:/ p>
- 如果T是类类型,则调用默认构造函数以提供新对象的初始值。
- 如果T是数组类型,则数组的每个元素都是默认初始化的。
- 否则,什么也不做。
由于 std :: vector
一个类类型的默认构造函数被调用。因此不需要手动初始化。
// Method One
class ClassName
{
public:
ClassName() : m_vecInts() {}
private:
std::vector<int> m_vecInts;
}
// Method Two
class ClassName
{
public:
ClassName() {} // do nothing
private:
std::vector<int> m_vecInts;
}
Question> What is the correct way to initialize the vector member variable of the class? Do we have to initialize it at all?
解决方案
See http://en.cppreference.com/w/cpp/language/default_initialization
Default initialization is performed in three situations:
- when a variable with automatic storage duration is declared with no initializer
- when an object with dynamic storage duration is created by a new-expression without an initializer
- when a base class or a non-static data member is not mentioned in a constructor initializer list and that constructor is called.
The effects of default initialization are:
- If T is a class type, the default constructor is called to provide the initial value for the new object.
- If T is an array type, every element of the array is default-initialized.
- Otherwise, nothing is done.
Since std::vector
is a class type its default constructor is called. So the manual initialization isn't needed.
这篇关于正确的方法来初始化向量成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文