代码之家  ›  专栏  ›  技术社区  ›  Nikit Batale

常量引用的文本初始化

  •  16
  • Nikit Batale  · 技术社区  · 16 年前

    const int &ref = 9;
    const int &another_ref = ref + 6;
    

    当非const引用不允许时,C++为什么允许对const引用进行文字初始化?例如。:

    const int days_of_week = 7;
    int &dof = days_of_week; //error: non const reference to a const object
    

    这可以通过以下事实来解释:非常量引用可用于更改它所引用的变量的值。因此,C++不允许对const变量进行非const引用。

    这可能是一种解释吗?C++不允许:

    int &ref = 7;
    

    因为这不符合逻辑,但是:

    const int &ref = 7;
    

    几乎相当于:

    const int val = 7;
    

    P.S:我现在是studying Lippman的C++入门。

    3 回复  |  直到 16 年前
        1
  •  14
  •   anon anon    16 年前

    因此,您可以编写如下代码:

    void f( const string & s ) {
    }
    
    f( "foobar" );
    

    string( "foobar" );
    

    这个无名字符串被绑定到引用。

    请注意,在创建非参数引用变量时,实际上非常不寻常——引用的主要目的是用作函数参数和返回值。

        2
  •  12
  •   Roger Pate Roger Pate    16 年前

    int const& ans = 42;
    // tranformed:
    int __internal_unique_name = 42;
    int const& ans = __internal_unique_name;
    

    或者当生命周期未延长时,例如函数参数:

    f("foobar");
    // transformed:
    {
      string __internal_unique_name = "foobar";
      f(__internal_unique_name);
    }
    

    (注意本例中的显式块。)

    虽然在非常量的情况下可能做类似的事情,但在CurrcTC++中,这是不允许的。然而,C++0x(下一个标准)将有r值引用。


    如果不清楚, ref + 6 从代码中创建一个临时对象,可以将其可视化为:

    int const& ref = int(9);
    int const& another_ref = int(ref + 6);
    
    // transformed:
    int __A = 9;
    int const& ref = __A;
    int __B = ref + 6;
    int const& another_ref = __B;
    

    这可能会帮助您理解/可视化正在发生的事情,但您不应该像这样编写真正的代码。我还使用了双下划线名称来说明这些名称是实现细节(由编译器使用),您不应该使用它们。任何包含相邻下划线的名称都保留给C++实现。

        3
  •  2
  •   Void - Othman    16 年前

    您的代码归结为C++标准规则,其中临时值的生存期绑定到 const 指定给它的引用。见 GoTW 文章 GotW #88: A Candidate For the “Most Important const” 了解更多详细信息。

    例如 ScopeGuard Generic: Change the Way You Write Exception-Safe Code — Forever “取决于这种行为。