流输入运算符导致 clang 出现分段错误,但适用于 gcc

Stream input operator causes Segmentation fault with clang but works with gcc

以下代码在使用 clang 编译并链接到 libc++ 时会导致段错误,但在使用 libstc++ 或使用 gcc 编译时工作正常。

#include <iostream>
#include <sstream>

class MyStream : public std::ostream {
public:
    MyStream() {
        rdbuf( &buffer );
    }

private:
    std::stringbuf buffer;
};

int main() {
    MyStream stream{};
    stream << "Hello world" << std::endl;
    return 0;
}

Here is the code on wandbox

尝试这样的事情:

#include <new>

class MyStream : public std::ostream {
public:
    MyStream() : std::ostream( new (buffer) std::stringbuf ) { }
    ~MyStream() {
        using std::stringbuf;
        ((stringbuf*)buffer)->~stringbuf();
    }
private:
    char buffer[sizeof(std::stringbuf)];
};

这应该首先通过 placement new 初始化缓冲区,然后允许您将其传递给 ostream