类中引用成员的初始化

时间:2022-09-09 15:11:35

1. A hard-to-find problem

See the following code snippet:

class Test
{
public:
    Test(int val) : ref_(val){}
    ~Test() {}
private:
    int & ref_;
};
 
int main()
{
    Test t(1);
 
    return 0;
}

 

what problem do you see? Maybe nothing.

Yeah, you initialize the Test::ref_ by a value of type "int", that's ref_(val)

but if you try directly:

int & ref1 = 2; // complier complain!

why?

Actually, the Test::ref_ is initialized in the constructor, a FUNCTION. That's mean ref_ is initialized by an automaic variable(formal argument val), not just a literation constant like 2. So that's true at 1st snippet.

But you can't initialize a non-const reference directly by a literation constant in 2nd snippet. Instead, you can do:

const int & ref2 = 3;

Here, a temporary with type of const int have been generated, and then this temporary can initialize the const int & reference.

Specially, in the following case, an extra type conversion has occured before the initialization:

const double & ref3 = 4;

2. Problem again and improvement

In 1st snippet, the Test::ref_ actually refers to an automatic variable, which have been destroyed after constructor invocation. So the approach for initializing the member of reference type is terriblely dangerous!

A possible approach is like this:

class Test
{
public:
    Test(int &val) : ref_(val){}
    ~Test() {}
private:
    int & ref_;
};
 
int main()
{
    Test t(1);
 
    return 0;
}

3. Why must use member initialization list for reference data member and const data member?

First, you should understand the advantage of member initialization list.

In 3 cases, you must use member initialization list:

1) Object member(no built-in type)

2) const member

3) reference member

Because const and reference type must intialize when declaration(defination), you cannot just declare without initialization them at first, and then initialize them by assignment.

So it's very important to differentiate the distinction between initialization and assignment. At fact, the complier can strictly disguish the difference!

You can try:

class Test
{
public:
    Test(char ch, int &val) { ch_=ch; ref_=val; }
    ~Test() {}
private:
    const char ch_;
    int & ref_;
};
 
int main()
{
    int a=2;
    Test t('c', a);
 
    return 0;
}
 

This time, the complier will complain some warnings.. ah

------
assignment of read-only data-member `Test::ch_'    main.cc    cpp    4    C/C++ Problem
uninitialized member `Test::ch_' with `const' type `const char'    main.cc    cpp    4    C/C++ Problem
uninitialized reference member `Test::ref_'    main.cc    cpp    4    C/C++ Problem

Summary:

1) All the operations in the body of contructor are regarded as assignment but not initialization.

2) reference and const type MUST be initialized when and only when they are declared(defined, if exactly speaking).