必须在构造函数初始化列表中初始化引用类型? [英] Must a reference type be initialized in constructor initialization list?

查看:172
本文介绍了必须在构造函数初始化列表中初始化引用类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为自我练习,我写了这个简单的代码:

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:

错误C2758:'Array< T> :: m_anchor':必须在构造函数库/成员初始化器列表中初始化

它从来没有发生,什么让我问这个问题:

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?

这篇关于必须在构造函数初始化列表中初始化引用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆