C++ 将temp分配给const ref成员会导致分段错误

C++ 将temp分配给const ref成员会导致分段错误,c++,constructor,temporary-objects,const-reference,C++,Constructor,Temporary Objects,Const Reference,最好用一个例子来解释: 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())? altDe

最好用一个例子来解释:

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;
};
#包括
静态常量字符*defaultDelim=“,;”;
类标记器{
公众:
标记器():
//“delim”是由临时字符串初始化的常量ref成员
delim((altDelim.size())?altDelim:std::string(defaultDelim))
{}
大小扫描(常量标准::字符串和字符串)
{return str.find_first_of(delim);}
静态void setDelim(const std::string&d){altDelim=d;}
私人:
静态std::字符串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;
}
#包括
使用名称空间std;
#包括“tok.h”
std::字符串标记器::altDelim;
int main()
{
标记器;
size_t pos=tok.scan(“你好,世界”);

cout该规则不适用于类成员。这在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.
{
}

说真的,我不明白为什么没有人投票支持这件事。今天很慢(