C++ 初始化向量成员变量的正确方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11725413/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:28:51  来源:igfitidea点击:

Correct way to initialize vector member variable

c++

提问by q0987

// 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?

问题> 初始化类的vector成员变量的正确方法是什么?我们必须初始化它吗?

采纳答案by Zeta

See http://en.cppreference.com/w/cpp/language/default_initialization

请参阅http://en.cppreference.com/w/cpp/language/default_initialization

Default initialization is performed in three situations:

  1. when a variable with automatic storage duration is declared with no initializer
  2. when an object with dynamic storage duration is created by a new-expression without an initializer
  3. 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.

默认初始化在三种情况下执行:

  1. 当没有初始化程序声明具有自动存储持续时间的变量时
  2. 当具有动态存储期的对象由没有初始化程序的 new 表达式创建时
  3. 构造函数初始值设定项列表中未提及基类或非静态数据成员并且调用该构造函数时

默认初始化的效果是:

  • 如果 T 是类类型,则调用默认构造函数为新对象提供初始值
  • 如果 T 是数组类型,则数组的每个元素都是默认初始化的。
  • 否则,什么都不做。

Since std::vectoris a class type its default constructor is called. So the manual initialization isn't needed.

由于std::vector是类类型,因此调用了它的默认构造函数。所以不需要手动初始化。

回答by juanchopanza

It depends. If you want a size 0 vector, then you don't have to do anything. If you wanted, say, a size N vector fill of 42s then use the constructor initializer lists:

这取决于。如果你想要一个大小为 0 的向量,那么你不必做任何事情。如果你想要一个大小为 42s 的 N 向量填充,那么使用构造函数初始值设定项列表:

ClassName() : m_vecInts(N, 42) {}

回答by mrts

Since C++11, you can also use list-initialization of a non-static member directly inside the class declaration:

从 C++11 开始,您还可以直接在类声明中使用非静态成员的列表初始化:

class ClassName
{
public:
    ClassName() {}

private:
    std::vector<int> m_vecInts = {1, 2, 3}; // or just {}
}

回答by mathematician1975

You do not have to initialise it explcitly, it will be created when you create an instance of your class.

您不必显式初始化它,它将在您创建类的实例时创建。