Reference variable in class definition
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 initia开发者_如何学Golized to? Or, is it an "uninitialized reference" of some sort, or something else?
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)
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;
};
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.
精彩评论