std::variant<std::string_view, std::string> result_message;

Viewed 67

I have a json-response from a web server containing several known "response codes". For those, I have constexpr return codes which can be returned by std::string_view. I want to prevent the copy there. But I have also one (can be extended later) response string, which have to be generated, in a case, where the message can't be parsed or another error occurs.

Now I have 3 solutions I thought about, but I don't know which is conceptually the best.

  1. Return a std::variant<std::string_view, std::string>
  2. Throw an exception for the unlikely case, that a std::string has to be generated.
  3. Create a static thread_local std::string, storing the last error and return a string_view.

I don't like any version:

3: Prone to dangling references, since the buffer of string can change. 2: Does not scale well, in the case, that a normal generated response will be added. 1: Extra indirection on each access. Increases code size and complexity.

What do you think?

0 Answers
Related