必须在构造函数初始化列表中初始化引用类型吗?
作为自我练习,我写了这个简单的代码:
As self-exercise, I have written this simple code:
#include <iostream>
int gIndex = 3;
template <class T> class Array
{
public:
explicit Array(int size);
T& operator[](int i) { return m_data[i]; }
T operator[](int i) const { return m_data[i]; }
T getAnchorPoint() const { return m_data[m_anchor]; }
private:
T* m_data;
int m_size;
int& m_anchor;
};
template <class T> Array<T>::Array(int size) : m_size(size), m_data(new T[size])
{
memset(m_data, 0, size*sizeof(T));
m_anchor = gIndex;
}
int main()
{
Array<double> a(10);
return 0;
}
我收到一个编译错误,内容为:
I got a compilation error , which says:
error C2758: 'Array
从来没有发生过,是什么让我问这个问题:
It has never happened , what brings me to ask this question:
必须在构造函数初始化列表中初始化任何类成员引用类型吗?
Must any class-member reference type be initialized in the constructor initialization list?
如果是,为什么?这与永远不能重新分配引用类型的事实有某种关系吗?
If so, why? Is that related somehow to the fact that a reference type can never be reassigned?
在构造函数初始化列表中是否有更多类型必须初始化?
Are there more types that must be initialized in constructor initialization list?
推荐答案
是否必须在构造函数初始化列表中初始化任何类成员引用类型?
Does any class-member reference type must be initialized in the constructor initialization list?
是的.
如果是,为什么?这是否与永远不能重新分配引用类型这一事实有关?
If so, why? Is that related somehow to the fact the a reference type can never be reassigned?
这是部分原因.另一部分是因为引用必须被初始化,而且它没有默认构造函数.
That's part of the reason. The other part is because a reference must be initialized, and it has no default constructor.
在构造函数初始化列表中是否有更多类型必须初始化?
Are there more types that must be initialized in constructor initialization list?
任何没有赋值运算符(复制或移动)或默认构造函数的类型.这显然包括(但不限于)const
成员,因为它们一旦构建就无法修改.
Any type that doesn't have an assignment operator (be it copy or move) or default constructor. This obviously includes (but is not limited to) const
members as they can't be modified once they've been constructed.
根据经验,你应该(几乎)总是喜欢在构造函数的初始化列表中初始化你的成员:为什么浪费循环首先默认构造一个对象,然后才分配给它(如果这甚至可能的话),当你一开始就可以正确构建它?
As a rule of thumb, you should (almost) always prefer to initialize your members in the constructor's initialization list: why waste cycles first default-constructing an object and then only assigning to it (if this is even possible), when you could construct it correctly in the first place?
相关文章