代码之家  ›  专栏  ›  技术社区  ›  Francis Cugler

与常量字符串相比,用户定义的字符串文字

  •  2
  • Francis Cugler  · 技术社区  · 7 年前

    考虑以下具有这两种结构的代码:

    std::string operator"" _str(const char* str, std::size_t len) {
        return std::string( str, len );
    }
    
    struct MessageLiterals {
        std::string HELP  = "Press F1 for help"_str;
        std::string ABOUT = "Press F2 for about"_str;
        std::string EXIT  = "Press ESC to exit"_str;
    };
    
    struct MessageConst {
        const std::string HELP { "Press F1 for help" };
        const std::string ABOUT { "Press F2 for about" };    
        const std::string EXIT { "Press ESC to exit" };
    };
    
    int main() {
    
        MessageLiterals ml;
        std::cout << "Using Literals:\n";
        std::cout << ml.HELP << std::endl;
        std::cout << ml.ABOUT << std::endl;
        std::cout << ml.EXIT << std::endl;
        std::cout << std::endl;
    
        MessageConst mc;
        std::cout << "Using Constant Strings:\n";
        std::cout << mc.HELP << std::endl;
        std::cout << mc.ABOUT << std::endl;
        std::cout << mc.EXIT << std::endl;
    
        std::cout << "\nPress any key and enter to quit." << std::endl;
        char c;
        std::cin >> c;
    
        return 0;
    }
    

    1. 尽管它们产生相同的结果,但它们是否被视为等效?
      • 等价于“内存足迹”、“编译运行时效率”等。
    2. 每种方法的优缺点是什么。
    3. 两者之间有什么优缺点吗?

    我刚想到 user-defined literals 我试图更好地理解它们的功能和有用性。

    编辑

    好的,对那些试图回答的人来说有点困惑。我熟悉 const . 这个问题似乎不止一个。但一般来说,我的想法很难用文字或问题的形式表达出来,但我试图得出的这两者之间区别的总体概念是:使用“常量std::strings”与“用户定义的字符串文字”之间有什么主要区别吗?

    2 回复  |  直到 7 年前
        1
  •  3
  •   Vittorio Romeo    7 年前
    std::string HELP  = "Press F1 for help"_str;
    

    std::string HELP  = "Press F1 for help";
    

    std::string 可以从C样式字符串构造。


    尽管它们产生相同的结果,但它们是否被视为等效?

    除非编译器可以执行一些更激进的优化,因为 const ,它们是相同的。


    每种方法的优缺点是什么。

    常数 防止字符串常数的意外突变。


    你不需要使用 标准::字符串 这里是编译时常数,可以是 constexpr :

    struct MessageConst {
        static constexpr const char* HELP { "Press F1 for help" };
        static constexpr const char* ABOUT { "Press F2 for about" };    
        static constexpr const char* EXIT { "Press ESC to exit" };
    };
    

    上面的代码保证没有动态分配,并确保可以在编译时计算常量。

        2
  •  1
  •   gsamaras a Data Head    7 年前

    两者之间有什么优缺点吗?

    可读性 结构内部。

    我能立刻理解里面发生了什么 MessageConst ,但我需要一两分钟来理解 MessageLiterals


    一个问题中的问题太多,哪里应该有一个问题。