例でよりよく説明します:
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 を出力します。実際のコードでは、セグ フォールトが発生します。
ここでは、const 参照に割り当てられた temp の寿命を延ばすという規則が成り立つと思いますが、明らかにそうではありません。その理由を知っていますか?