【问题标题】:assigning a temp to a const ref member causes a segmentation fault将 temp 分配给 const ref 成员会导致分段错误
【发布时间】:2012-07-07 18:14:09
【问题描述】:

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

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

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

【问题讨论】:

    标签: c++ constructor temporary-objects const-reference


    【解决方案1】:

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

    【讨论】:

    • 点对点,我不明白为什么没有对此表示赞同。今天慢了一天。 :(
    猜你喜欢
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多