在成员初始化器列表中,我可以创建对不在列表中的成员变量的引用吗? [英] In the member initializer list, can I create a reference to a member variable not in the list?

查看:67
本文介绍了在成员初始化器列表中,我可以创建对不在列表中的成员变量的引用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

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

推荐答案

您可以这样做 1 ,因为:


  1. x y 都已经在范围内( [basic.scope.class] / 1 )。

  2. 由于您在构造函数开始执行后获得了引用( [class .cdtor] / 1 )和 y 的存储已获得( [basic.life] / 7 ),则该引用可以绑定到 y

  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.

在构造函数的复合语句中使用该引用(在成员初始化结束之后)也可以。这是因为 y 被视为已初始化,并且 x 现在引用其生存期已开始的对象。

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 -语言律师需要注意。从技术上讲,引用需要绑定到有效对象( [dcl.ref ] / 5 ),表示其生命已经开始。但是,例如核心语言问题363 详细信息,它有望工作! 核心语言问题中讨论了有问题的措词和可能的解决方法453 (在删除的评论中由@TC提供)。该标准中有一个错误,但是您的代码本来应该是格式正确的,并且实现通常都知道这一点。

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.

这篇关于在成员初始化器列表中,我可以创建对不在列表中的成员变量的引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆