gpt4 book ai didi

c++ - 将 char 添加到 String 并删除 char 数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:57:13 24 4
gpt4 key购买 nike

正在将 char* 中的 char 添加到 std::string,然后 delete[] char 数组会导致 UB?

或者在 delete[] 之后处理字符串是否安全?

int buffer_size = 4096;
char* buffer = new char[buffer_size];

//here there was removed code that assign values to the buffer[i]

std::string data;

for (int i = 0; i < buffer_size ; i++)
{
data.push_back(buffer[i]);
}

delete[] buffer;

//is the data string content secured at this point?

最佳答案

push_back函数的定义是

void push_back( CharT ch );    

由于参数 ch 是按值而不是按引用传递的,因此它被复制到字符串中,因此删除附加到字符串的 char 的源不会导致任何问题。

关于c++ - 将 char 添加到 String 并删除 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55218341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com