c++ - 是 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
数组而不是字符串。
解决方案
推荐阅读
- sql-server-2016 - SQL Server 复制作业错误:消息:命令文本:SELECT TOP 1 0 FROM [dbo].[tablename] WITH (TABLOCK, HOLDLOCK)
- android - 总是收到错误消息:在重力左侧找不到抽屉视图
- dart - 实现广度优先搜索算法时出现内存不足错误
- ios - 我必须每年使用 Enterprise Licensing 发布一个新的 iOS 版本吗?
- javascript - 功能组件内的状态初始化(无无限循环)
- idris - 在 Idris 中定义组
- php - 单元测试 Mail::send()
- c - 从内存中删除整个二叉树
- android - Android LibVLC,在没有 TextureView 的情况下拍摄 RTSP 流的快照
- spring-boot - 由使用 @Inject 的第 3 方库实现的 Spring Bean 与 Spring 的注入机制冲突