给出代码
// somewhere in the program const char* p1 = "Hello World"; // somewhere else in the program const char* p2 = "Hello World";是否可以确保 p1 == p2 是否始终在整个程序/库中满意?我的意思是 p1 和 p2 总是引用相同的字符串文字。
is there a way to ensure that p1 == p2 is always satisfied within the entire program / library? By that I mean that p1 and p2 always refer to the same string literal.
我要实现的目标是使用 const char * 作为 std :: map< const char *,something> 的键。我有一个宏
What I'm trying to achieve is to use const char* as a key for std::map<const char*, something>. I have a macro
#define nameof(id) #id模仿了C#中 nameof 关键字的行为(我知道这已经存在缺陷),我想使用它来访问类似结构的注册表,例如
that mimics the behavior of the nameof keyword in C# (I know this is already flawed) and I want to use it to access a registry like structure, for example
void foo() { auto x = getMapping(nameof(foo)); } // different place in code void registerFoo(something x) { setMapping("foo", x); }推荐答案
如Barry在他们的答案不能保证您想要的行为。您将不得不支付字符串比较的费用,但是您至少可以避免使用 std :: string_view 。 std :: string_view 是字符串的轻量级视图,其中包含指向字符串数据和字符串大小的指针,并且内置了运算符< 进行字典比较。这样会将您的地图更改为
As Barry shows in their answer the behavior you want is not guaranteed. You're going to have to pay the cost of string comparisons, but you can at least avoid any memory allocations or writing a comparator by using a std::string_view. A std::string_view is a lightweight view of a string that holds a pointer to the string data and the size of the string and it has a built in operator < that will do a lexicographical comparison. That would change your map to
std::map<std::string_view, something>更多推荐
确保char指针始终指向相同的字符串文字
发布评论