3

N3290 C++ ドラフトからのポイント、§ 12.2、5 番目のポイント、10 行目。

2 番目のコンテキストは、参照がテンポラリにバインドされる場合です。参照がバインドされている一時オブジェクト、または参照がバインドされているサブオブジェクトの完全なオブジェクトである一時オブジェクトは、次の例外を除き、参照の存続期間中持続します。

new-initializer (5.3.4) の参照への一時的なバインドは、new-initializer を含む full-expression が完了するまで持続します。[ 例:

struct S { int mi; const std::pair<int,int>& mp; };
S a { 1, {2,3} };
S* p = new S{ 1, {2,3} };// Creates dangling reference

— 例の終了 ] [ 注: これによりダングリング参照が導入される可能性があり、実装はそのような場合に警告を発行することをお勧めします。— エンドノート]

これは、C++03 と比較した場合の追加ポイントです。しかし、その例は私には理解できません。この点を他の例で説明していただけますか?

ダングリング参照と一時オブジェクトが何であり、std::pairデータ型が異なる可能性のある 2 つの値を保持することを知っています。

4

1 に答える 1

7

一般に、テンポラリは、それらが作成された式の最後までしか持続しません:

#include <complex>


void func()
{
    std::complex<int>   a; // Real variable last until the end of scope.

    a = std::complex<int>(1,2) + std::complex<int>(3,4);
     // ^^^^^^^^^^^^^^^^^^^^^^  Creates a temporary object
     //                         This is destroyed at the end of the expression.
     // Also note the result of the addition creates a new temporary object
     // Then uses the assignment operator to change the variable 'a'
     // Both the above temporaries and the temporary returned by '+'
     // are destroyed at ';'

一時オブジェクトを作成して参照にバインドする場合。その寿命を、それがバインドされている参照と同じ寿命まで延長します。

    std::complex<int> const& b  = std::complex<int>(5,6);
                      //           ^^^^^^^^^^^^^^^^ Temporary object
                      // ^^^^                       Bound to a reference.
                      //                            Will live as long as b lives 
                      //                            (until end of scope)

このルールの例外は、テンポラリが新しいイニシャライザの参照にバインドされている場合です。

    S* p1 = new S{ 1, {2,3} };
    // This is the new C++11 syntax that does the `equivalent off`:

    S* p2 = new S {1, std::pair<int,int>(2,3) };
                 //   ^^^^^^^^^^^^^^^^^^^^^^^    Temporary object.
                 //                              This lives until the end of the 
                 //                              expression that belongs to the new.
                 //                              ie the temporary will be destroyed
                 //                              when we get to the ';'

しかし、ここでは新しい一時オブジェクトをメンバーにバインドしています

const std::pair<int,int>& mp;

これは const 参照です。ただし、バインドされている一時オブジェクトは「;」で破棄されます したがって、mp は、後続の式で使用しようとすると存在しなくなったオブジェクトへの参照になります。

}
于 2011-09-12T11:02:38.247 に答える