Reference variable in class definition

筅森魡賤 提交于 2019-12-20 21:47:23

问题


I am learning C++, and I read that all references must be initialized upon declaration, and there can be no "uninitialized references". But what if the reference variable is a class member?

class test
{
    int &k;
};

int main()
{
    test *abc = new test;
}

This program compiles and runs normally (in g++, no warnings). However, abc->k is a reference, but what is it initialized to? Or, is it an "uninitialized reference" of some sort, or something else?


回答1:


The program is ill-formed because it constructs a class that fails to initialize a non-static member entity of reference type.

I believe that gcc should fail to compiler this, but I only received the warning "non-static reference ‘int& test::k’ in class without a constructor".

test is a non-POD-struct type as it contains a reference member. (9 [class] / 4)

new test default-initializes the dynamically allocated class. (5.3.4 [expr.new] / 15)

To default-initialize an object of type test means to call the implicitly declared and implicitly defined default constructor. (8.5 [dcl.init] / 5)

The implicitly defined default constructor is equivalent to a default constructor with an empty mem-initialized-list and an empty function body. (12.1 [class.ctor] / 7)

Further more:

The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with an empty mem-initializer-list (12.6.2) and an empty function body. If that user-written default constructor would be ill-formed, the program is ill-formed.

If an entity is not name in a mem-initializer-list and the member is not of class type [with further restrictions] then the entity is not initialized.

Otherwise, the entity is not initialized. If the entity is of const-qualified type, or reference type, [or ...] the program is ill-formed." (12.6.2 [class.base.init] / 4)




回答2:


Your code actually wont compile at all on Visual C++. In general it best to leave as little to chance as possible. You need to initialize refence members using an initialiser list in the constructor:

class test
{
public:
 test(int& x) : k(x)
 {
 }
 int& k;
};



回答3:


class test
{
    public:
        test(int x) : k(x)
        {
        }
    int& k;
};

I have doubt on the way reference is being initialized. When stack frame for ctr is taken off the stack, the reference will no longer be valid.



来源:https://stackoverflow.com/questions/5049891/reference-variable-in-class-definition

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!