给定代码
// somewhere in the program
const char* p1 = "Hello World";
// somewhere else in the program
const char* p2 = "Hello World";
有没有办法确保p1 == p2
在整个程序/库中总是满意吗?我的意思是p1
和 p2
始终引用相同的字符串文字。
背后的原因
我想要实现的是使用 const char*
作为 std::map<const char*, something>
的键.我有一个宏
#define nameof(id) #id
模仿 nameof
的行为C# 中的关键字(我知道这已经有缺陷),我想用它来访问注册表之类的结构,例如
void foo()
{
auto x = getMapping(nameof(foo));
}
// different place in code
void registerFoo(something x)
{
setMapping("foo", x);
}
最佳答案
正如 Barry 在 their answer 中展示的那样无法保证您想要的行为。您将不得不支付字符串比较的成本,但您至少可以避免任何内存分配或使用 std::string_view
编写比较器。 . std::string_view
是一个字符串的轻量级 View ,它包含一个指向字符串数据的指针和字符串的大小,并且它有一个内置的 operator <
。那将进行字典顺序比较。这会将您的 map 更改为
std::map<std::string_view, something>
关于c++ - 确保 char 指针始终指向相同的字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58866964/