【问题标题】:std::string addition to char*std::string 添加到 char*
【发布时间】:2019-07-15 07:32:02
【问题描述】:

我试图了解将 std::string 添加到 char* 的工作原理。 此代码正在按预期编译和工作:

#include <string>
#include <cstdio>

void func (const char* str) {
  printf("%s\n", str);
}

int main () {
  char arr[] = {'a','b','c',0};
  char *str = arr;
  func((str + std::string("xyz")).c_str()); // THIS LINE
  return 0;
}

但我不明白调用的是什么构造函数/方法以及它的工作顺序。这是将 std::string 添加到 char* 中,它给出了另一个 std::string,但 char* 不是一个类,它没有加法运算符。

【问题讨论】:

  • std::string 有一个重载的operator+,它在左侧接受char*。结果是std::string。 (因此,需要.c_str()。)额外信息:临时加法结果的生命周期足够长以完成调用(无法访问丢失的std::string)。

标签: c++ stdstring


【解决方案1】:

您将operator + 用于左侧的const char*,并在右侧使用临时的std::string。这是重载 #4 here:

template< class CharT, class Traits, class Alloc >
basic_string<CharT,Traits,Alloc>
    operator+( const CharT* lhs,
               const basic_string<CharT,Traits,Alloc>& rhs );

返回值

包含 lhs 中的字符后跟 rhs 中的字符的字符串

有了std::stringchar,上面的模板签名可以“解释”为

std::string operator+ (const char* lhs, const std::string& rhs);

结果是一个新的临时 std::string 对象,它拥有连接的新缓冲区 "abcxyz"。可以绑定const char*类型的函数参数,只要函数体执行就有效。

【讨论】:

    【解决方案2】:

    这一行:

    str + std::string("xyz")
    

    调用以下运算符:

    https://en.cppreference.com/w/cpp/string/basic_string/operator%2B
    
    template< class CharT, class Traits, class Alloc >
        basic_string<CharT,Traits,Alloc>
            operator+(const CharT* lhs,
                      basic_string<CharT,Traits,Alloc>&& rhs );
    

    并创建一个临时的std::string(在完整语句结束前有效),您可以在其上调用.c_str(),返回const char*,并传递给函数。

    【讨论】:

      猜你喜欢
      • 2011-11-13
      • 2011-10-26
      • 2017-08-22
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-09
      相关资源
      最近更新 更多