考虑以下具有这两个结构的代码:
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;
}
两人之间想到了几个问题。
- 虽然它们产生相同的结果,但它们是否被认为是等效的?
- 相当于“内存占用”、“编译运行时间效率”等手段。
- 各自的优点/缺点是什么。
- 与其他方面相比,有什么优点或缺点吗?
我刚刚遇到了用户定义文字
的概念,我正在尝试更好地理解它们的功能和用途。
编辑
好吧,对于那些试图回答的人来说有点困惑。我熟悉 const 的使用。问题似乎不止一个。但一般来说,我的想法很难用语言或问题的形式表达出来,但我试图理解的两者之间差异的总体概念是:使用“constant std:”之间是否有任何重大差异: :strings”优于“用户定义的字符串文字”?
最佳答案
std::string HELP = "Press F1 for help"_str;
与
没有什么不同std::string HELP = "Press F1 for help";
std::string
可以从 C 样式字符串构造。
Are these considered equivalent or not although they produce the same result?
除非编译器可以通过 const
执行一些更积极的优化,否则它们是相同的。
What are the pros/cons of each.
const
防止字符串常量的意外突变。
您不需要在此处使用 std::string
- 您拥有可以是 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" };
};
上面的代码保证不进行动态分配,并确保可以在编译时评估常量。
关于c++ - 用户定义的字符串文字与常量字符串的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47472589/