簡體   English   中英

為const引用成員分配temp會導致分段錯誤

[英]assigning a temp to a const ref member causes a segmentation fault

通過一個例子更好地解釋:

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這是錯誤的。 真正的代碼會出現seg錯誤。

我希望延長分配給const引用的temp的壽命的規則會在這里保留,但顯然不是。 你知道原因嗎?

該規則不適用於班級成員。 這在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.
{
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM