5

通过一个例子更好地解释:

托克.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;
};

主文件

#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 的生命周期的规则在这里会成立,但显然不是。你知道原因吗?

4

1 回答 1

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.
{
}
于 2012-07-07T16:11:05.363 回答