首页 > 解决方案 > 是 const_cast(const char*) 在 std::string::data() 的情况下未定义的行为?

问题描述

std::string&在函数中有参数,需要访问它的存储并用新字符串修改它。

我一般不知道(不仅仅是 std::string 数据)const_cast反对const char*是否会导致未定义的行为?

例如,它看起来像这样:

// method 1
void foo(std::string& ref_param)
{
      const_cast<char*>(ref_param.data()) = "this is new string";
}

// method 2
void bar(std::string param)
{
     foo(param);
}

int main()
{
      bar("initial string");
      return 0;
}

我不能只为字符串分配新值,因为调用函数接受char数组而不是字符串。

标签: c++string

解决方案


推荐阅读