在C++中高效传递字符串文本

Efficient passing of string literals in C++

本文关键字:字符串 文本 高效 C++      更新时间:2023-10-16

在编写包装Lua的代码时,我遇到了传递字符串文字的需求,并开始想知道哪种方式最有效。

我可以在两个功能之间进行选择:

  1. void lua_pushstring (lua_State* L, const char* str);
  2. void lua_pushlstring(lua_State* L, const char* str, size_t len);

当然,第一个函数在内部使用strlen(),因此第二个函数更快。

现在,如果在编译时知道它,我想避免计算字符串长度,如此处和此处所述:

// Overload 1
template <size_t N>
inline void pushstring(lua_State* L, const char (&str) [N])
{
    lua_pushlstring(L, str, N-1);
}

当使用字符串文字调用时,这个函数工作得很好:pushstring(L, "test");当然,当用const char*调用时,它不会编译,例如在.cpp文件中的较长函数中:

// this is in a .cpp file
void long_function(lua_State* L, const char* str)
{
    // do lots of stuff
    pushstring(L, str);  // compile error
    // do more stuff
}

现在如果我添加

// Overload 2
inline void pushstring(lua_State* L, const char* str)
{
    lua_pushstring(L, str);
}

由于某种原因(C++重载分辨率很棘手)它优于Overload 1,因此永远不会被调用。

有没有聪明的方法来解决这个问题?

我会提供两个选项:

void f( const char*, int );
template <int N> void f( const char (&str)[N] ) {
   f( str, N-1 );
}

(或者更确切地说是std::size_t),现在具有字符串文本的用户可以调用将在内部调度到第一个的第二个。没有文字但有const char*的用户负责提供正确的大小。

如果将第二个转发到第一个声明两者

void lua_pushlstring(lua_State* L, const char* str, size_t len);
inline void lua_pushstring (lua_State* L, const char* str)
{ lua_pushlstring(L, str, strlen(str)); }

然后,当您使用文字调用第二个函数时,一个体面的编译器将优化strlen调用,例如,它将内联

lua_pushstring(L, "hello");

并且由于文本上的strlen可以优化为常量,因此它将用调用以下命令替换它:

lua_pushlstring(L, "hello", 5);

这为您提供了调用双参数形式的简单语法,而无需支付文字strlen费用。

当长度已知时,可以传递:

lua_pushlstring(L, s.c_str(), s.length());

或者这也有效,但需要不必要的strlen

lua_pushstring(L, s.c_str());

要进一步详细说明您的模板版本:

#include <iostream>
template <typename T>
inline void pushstring(T str);
template <int N>
inline void pushstring(const char (&str) [N])
{
   std::cout << N << std::endl;
}
template <>
inline void pushstring(const char *str)
{
   std::cout << str << std::endl;
}

在此处查看测试运行:
错误的参数 ->链接器错误:http://ideone.com/vZbj6
Rigt 参数 -> 运行良好:):http://ideone.com/iJBAo