函数模板内的相同文本字符串
Same text string inside function template
将长消息字符串保留在函数模板之外更好,还是在这种情况下编译器总是创建该字符串的一个副本?我应该把 "Long error message" 放在模板函数之外吗?在单独的 printError
函数中?
template<typename T>
function f( ARGS )
{
if ( some_check(ARGS) )
cout << "Long error message independent of T";
...
}
编译器可能会为模板的每个实例创建字符串文字的副本,但除非您有几千字节的字符串,否则我怀疑它不会产生任何实际影响。如果您确实有一个过长的字符串,将其存储在函数模板之外就可以解决问题。
虽然这个问题的答案取决于链接器支持的内容,但您可以合理地确定,在启用任何级别的优化后,重复的字符串文字将合并为一个。
特别是,GCC 提供了合并重复全局常量的选项-fmerge-constants
which will merge identical constants, including string literals, across compilation units as long as the linker allows it. This is enabled at -O, O2, O3 and -Os
. Similarly, LLVM has an optimization pass, -constmerge
。
将长消息字符串保留在函数模板之外更好,还是在这种情况下编译器总是创建该字符串的一个副本?我应该把 "Long error message" 放在模板函数之外吗?在单独的 printError
函数中?
template<typename T>
function f( ARGS )
{
if ( some_check(ARGS) )
cout << "Long error message independent of T";
...
}
编译器可能会为模板的每个实例创建字符串文字的副本,但除非您有几千字节的字符串,否则我怀疑它不会产生任何实际影响。如果您确实有一个过长的字符串,将其存储在函数模板之外就可以解决问题。
虽然这个问题的答案取决于链接器支持的内容,但您可以合理地确定,在启用任何级别的优化后,重复的字符串文字将合并为一个。
特别是,GCC 提供了合并重复全局常量的选项-fmerge-constants
which will merge identical constants, including string literals, across compilation units as long as the linker allows it. This is enabled at -O, O2, O3 and -Os
. Similarly, LLVM has an optimization pass, -constmerge
。