确保char指针始终指向相同的字符串文字

编程入门 行业动态 更新时间:2024-10-23 12:33:46
本文介绍了确保char指针始终指向相同的字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出代码

// 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指针始终指向相同的字符串文字

本文发布于:2023-07-28 14:12:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1231656.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   指针   文字   char

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!