In my opinion, it is legal (well defined) to initialize a link with an uninitialized object. This is legal, but standard (well, the latest C ++ 11 project, clause 8.5.3.3) recommends using a valid (fully constructed) object as an initializer:
A reference shall be initialized to refer to a valid object or function.
The following sentence from the same paragraph makes link building a little easier:
[Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the "object" obtained by dereferencing a null pointer, which causes undefined behavior.]
I understand that creating links means linking the object to the object obtained by dereferencing its pointer, and this probably explains that the minimum prerequisite for initializing a link of type T & has the address of the part of memory reserved for an object of type T (reserved, but not yet initialized )
Accessing an uninitialized object through its link can be dangerous.
I wrote a simple test application that demonstrates link initialization with an uninitialized object and the consequences of accessing this object through it:
class C { public: int _n; C() : _n(123) { std::cout << "C::C(): _n = " << _n << " ...and blowing up now!" << std::endl; throw 1; } }; class B { public:
Output:
B::B(): &_ro_c = 001EFD70 &_c = 001EFD70 &_ro_c->_n = -858993460 &_c->_n = -858993460 C::C(): _n = 123 ...and blowing up now! Failed to create object of type A
Bojan komazec
source share