In the member initializer list, can I create a reference to a member variable not in the list?

  • A+
Category:Languages

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.)


You can do so because:

  1. x and y are both in scope already ([basic.scope.class]/1).
  2. Since you are obtaining a reference after the constructor started executing ([class.cdtor]/1) and storage for 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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: