Ensure that char pointers always point to the same string literal

前端 未结 4 1184
攒了一身酷
攒了一身酷 2021-01-16 12:18

Given the code

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

// somewhere else in the program
const char* p2 = \"Hello World\";
4条回答
  •  忘掉有多难
    2021-01-16 13:08

    Identical literal strings are not guaranty to be identical, but as you use MACRO to create the string, you can change it to return identical string.

    gcc/clang have an extension to allow to build UDL from literal string:

    template
    struct CsHelper
    {
        static constexpr const Char s[] = {Cs..., 0}; // The unique address
    };
    
    // That template uses the extension
    template
    constexpr auto operator"" _cs() -> const Char (&)[1 + sizeof...(Cs)] {
        return CsHelper::s;
    }
    

    and then

    #define nameof(id) #id ## _cs
    

    See my answer from String-interning at compiletime for profiling to have MAKE_STRING macro if you cannot used the extension (Really more verbose, and hard coded limit for accepted string length).

提交回复
热议问题