c++c++17stringstreamuser-defined-literals

User-defined literal for stringstream


I wrote an operator function that returns std::stringstream when suffix _f appears.

#include <iostream>
#include <sstream>
#include <utility>

static std::stringstream&& operator "" _f(const char* const s, const size_t _) {
    return std::move(std::stringstream() << s);
}

int main() {
    const auto s = "Number: "_f << 10 << '\n';
    std::cout << s.str();
    return 0;
}

However, when I run this I get a runtime exception: "Access violation reading location ...".

Can you please tell me, where's the mistake in my code?


Solution

  • The operator returns a reference to a temporary std::stringstream object inside the function, resulting in a dangling reference. You should return std::stringstream directly.

    static std::stringstream operator "" _f(const char* const s, const size_t _) {
        return std::stringstream() << s;
    }