2012-07-07 19 views
5

更好通過爲例進行了說明:分配一個臨時一個const REF構件使分割故障

tok.h

#include <string> 

static const char* defaultDelim = ".,;"; 

class Tokenizer { 
public: 
    Tokenizer(): 
     // 'delim' is the const ref member that is initialized by the temp string 
     delim((altDelim.size())? altDelim : std::string(defaultDelim)) 
    {} 

    size_t scan(const std::string& str) 
    { return str.find_first_of(delim); } 

    static void setDelim(const std::string& d) { altDelim = d; } 
private: 
    static std::string altDelim; 
    const std::string& delim; 
}; 

的main.cpp

#include <iostream> 
using namespace std; 

#include "tok.h" 

std::string Tokenizer::altDelim; 

int main() 
{ 
    Tokenizer tok; 

    size_t pos = tok.scan("hello, world"); 
    cout << pos << endl; 
} 

的程序打印0這是錯誤的。真正的代碼會得到一個seg錯誤。

我期望延長分配給const引用的temp的生命期限的規則在這裏可以保留,但顯然它不是。你知道原因嗎?

回答

4

該規則不適用於班級成員。這是在C++ 03標準12.2.5規定:

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

製作比臨時持續更長的時間將意味着臨時會必須保持作爲類的一部分,使得它的壽命可能會保持。如果構造函數位於單獨的編譯單元中,這將是不可能的,因爲在定義類時必須知道該類的大小。

// 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

現貨上,我不明白爲什麼沒有upvotes爲此。今天緩慢的一天。 :( – 2012-07-07 16:55:05

+0

簡潔而全面,非常感謝! – davka 2012-07-07 17:05:52