c++ - Reference variable in class definition -
i learning c++, , read references must initialized upon declaration, , there can no "uninitialized references". if reference variable class member?
class test { int &k; }; int main() { test *abc = new test; }
this program compiles , runs (in g++, no warnings). however, abc->k
reference, initialized to? or, "uninitialized reference" of sort, or else?
the program ill-formed because constructs class fails initialize non-static member entity of reference type.
i believe gcc should fail compiler this, received warning "non-static reference ‘int& test::k’ in class without constructor".
test
non-pod-struct type contains reference member. (9 [class] / 4)
new test
default-initializes dynamically allocated class. (5.3.4 [expr.new] / 15)
to default-initialize object of type test
means call implicitly declared , implicitly defined default constructor. (8.5 [dcl.init] / 5)
the implicitly defined default constructor equivalent default constructor empty mem-initialized-list , empty function body. (12.1 [class.ctor] / 7)
further more:
the implicitly-defined default constructor performs set of initializations of class performed user-written default constructor class empty mem-initializer-list (12.6.2) , empty function body. if user-written default constructor ill-formed, program ill-formed.
if entity not name in mem-initializer-list , member not of class type [with further restrictions] entity not initialized.
otherwise, entity not initialized. if entity of const-qualified type, or reference type, [or ...] program ill-formed." (12.6.2 [class.base.init] / 4)
Comments
Post a Comment