Consider:
#include <string>
#include <iostream>
class Foo
{
public:
Foo( char const * msg ) : x( y )
{
y = msg;
}
std::string const & x;
private:
std::string y;
};
int main( int argc, char * argv[] )
{
if ( argc >= 2 )
{
Foo f( argv[1] );
std::cout << f.x << std::endl;
}
}
This compiles and prints the first parameter... but I have doubts whether it is actually "legal" / well-formed. I know that the initializer list should initialize variables in order of their declaration in the class, lest you reference variables that haven't been initialized yet. But what about member variables not in the initializer list? Can I safely create references to them as showcased?
(The example is, of course, meaningless. It's just to clarify what I am talking about.)
There are three steps to initializing a reference variable from scratch: declaring the reference variable; using the new operator to build an object and create a reference to the object; and. storing the reference in the variable.
And in in computation phase which typically starts with the '{' of constructor body, if you do an assignment then compiler will complain as the reference member was already intialized. So, your only chance to initialize such member is the constructor initializer list.
A reference can be declared without an initializer: When it is used in a parameter declaration. In the declaration of a return type for a function call. In the declaration of class member within its class declaration.
To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.
You can do so1 because:
x
and y
are both in scope already ([basic.scope.class]/1).y
is obtained already ([basic.life]/7), that reference can be bound to y
.Using that reference inside the constructor's compound statement (after member initialization is all over) is also fine. That is because y
is considered initialized, and x
refers now to an object whose lifetime has started.
1 - There's a caveat for language lawyers. Technically, a reference needs to be bound to a valid object ([dcl.ref]/5), meaning one whose lifetime has started. However, like Core Language issue 363 details, it's expected to work! The problematic wording and a possible resolution is discussed in Core Language issue 453 (courtesy of @T.C. in a deleted comment). There's a bug in the standard, but your code is intended to be well formed, and implementations are generally aware of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With