Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do so1 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.


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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...