Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

c++ - Ensure that char pointers always point to the same string literal

Given the code

// somewhere in the program
const char* p1 = "Hello World";

// somewhere else in the program
const char* p2 = "Hello World";

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.

The Reason behind it

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

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...