Ale*_*ach 1 c++ string-literals
我有一个旧式的接口函数,经过一些重构,我需要返回其原始const char*指针,该指针不应被删除。
该函数如下所示:
const char* func()
{
...
return "Some string literal that contains some value to be moved out: VALUE";
}
Run Code Online (Sandbox Code Playgroud)
我需要将 VALUE 移到外面并在 return 语句中使用它,如下所示(组合 2 个字符串):
constexpr auto MY_VALUE = "VALUE";
const char* func()
{
...
static const std::string msg = "Some string literal that contains some value to be moved out: " + MY_VALUE;
return msg.c_str();
}
Run Code Online (Sandbox Code Playgroud)
但我不喜欢这个静态变量。
是否有另一种更好的方法来组合两个编译时已知的字符串文字?
另一种方法,不一定更好,具有#define:
#define MY_VALUE "VALUE"
const char* func()
{
return "Some string literal that contains some value to be moved out: " MY_VALUE;
}
Run Code Online (Sandbox Code Playgroud)