在异常消息中使用 constexpr

Use of constexpr in exception message

我试图在异常消息中使用 constexpr,但这不起作用: 以下代码在 g++ 上编译良好(使用 c++11 或 c++14)。

#include <exception>

constexpr auto TEST = "test";

class test_throw : public std::exception {
public:
    virtual const char* what() const throw() {
        return (std::string("THROW ")+TEST).c_str();
    }
};

int main()
{
    throw test_throw{};
} 

我想知道为什么我的异常输出的是空消息,好吧,这似乎是个坏把戏,但我不明白消息怎么会是空的。

有没有办法在不用宏替换 constexpr 的情况下实现这一点?

灾难正在等待 - 这是 gcc 的警告:

<source>: In member function 'virtual const char* test_throw::what() const':
9 : <source>:9:51: warning: function returns address of local variable [-Wreturn-local-addr]
         return (std::string("THROW ")+TEST).c_str();

这里有一些确保安全的方法:

选项 1 - 从更具体的标准异常派生,初始化 构造函数中的消息。

#include <stdexcept>
#include <string>

constexpr auto TEST = "test";

class test_throw : public std::runtime_error 
{
public:
    test_throw()
    : runtime_error(std::string("THROW ")+TEST)
    {}
};

选项 2 - 以 thread_safe 静态方式构建消息:

class test_throw : public std::exception 
{
public:
    const char* what() const noexcept
    {
        thread_local static std::string message;

        try
        {
            message = std::string("THROW ") + TEST;
            return message.c_str();
        }
        catch(...)
        {
            return "can't give you a message";
        }
    }
};

选项 3 - 重新发明轮子。

class test_throw : public std::exception 
{
    std::string message_;

public:
    test_throw()
    : message_ { std::string("THROW ") + TEST }
    {}

    const char* what() const noexcept
    {
        return message_.c_str();
    }
};