2012-07-07 19 views
5

lepiej wytłumaczyć na przykładzie:przypisanie do temp const członka ref powoduje błąd segmentacji

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; 
} 

się program wyświetla 0, która jest nieprawidłowa. Prawdziwy kod dostaje błąd seg.

Spodziewałbym się, że obowiązywałaby zasada przedłużania żywotności temp przypisanej do wartości odniesienia, ale najwyraźniej tak nie jest. Czy znasz przyczynę "?

Odpowiedz

4

Ta reguła nie dotyczy członków klasy. Jest to określone w 12.2.5 standardu C++ 03:

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

Making tymczasowej dłużej niż sugerowałoby, że tymczasowy musiałby być przechowywane jako część klasy, tak aby jego żywotność może być utrzymany. Byłoby to niemożliwe, gdyby konstruktor znajdował się w oddzielnej jednostce kompilacji, ponieważ rozmiar klasy musi być znany, gdy klasa jest zdefiniowana.

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

Odłóżmy to, nie rozumiem, dlaczego nie było w tym celu żadnych loterii. Dziś powolny dzień. :( –

+0

zwięzły i wszechstronny, dziękuję bardzo! – davka

Powiązane problemy