2012-07-07 7 views
5

良好セグメンテーション違反を引き起こしますプログラムは0を間違って表示します。実際のコードはsegフォールトを取得します。を例により説明

私はconst参照に割り当てられた一時的な温度の寿命を延ばすというルールがここにあると思いますが、明らかにそうではありません。理由を知っていますか? '

答えて

4

このルールはクラスメンバーには適用されません。一時的にその寿命があることができるように、クラスの一部として保持されなければならないことを暗示する一時的な最後のより長い作る

A temporary bound to a reference member in a constructor's ctor-initializer 
persists until the constructor exits. 

:これはC++ 03標準の12.2.5に記載されています維持された。クラスの定義時にクラスのサイズを知る必要があるため、コンストラクタが別のコンパイル単位にある場合は、これは不可能です。

// header file 
struct A { 
    A(); 
    B &b; 
}; 


// file1.cpp 
void f() 
{ 
    A a; // Reserve the size of a single reference on the stack. 
} 


// file2.cpp 
A::A() 
: b(B()) // b is referencing a temporary, but where do we keep it? 
     // can't keep the temporary on the stack because the 
     // constructor will return and pop everything off the stack. 
     // Can't keep it in the class because we've already said the 
     // class just contains a single reference. 
{ 
} 
+0

なぜ、これにアップフォースがないのかわかりません。今日はゆっくり。 :( –

+0

簡潔で包括的です。ありがとうございます! – davka