gpt4 book ai didi

c++ - std::string::assign 是否占用字符串的 "ownership"?

转载 作者:IT老高 更新时间:2023-10-28 12:59:40 34 4
gpt4 key购买 nike

我对string::assign方法的理解有些差距。考虑以下代码:

char* c = new char[38];
strcpy(c, "All your base are belong to us!");
std::string s;
s.assign(c, 38);

s.assign 是否分配一个新缓冲区并将字符串复制到其中,或者它假定指针的所有权;即不分配新内存并直接使用我的地址。如果是复制的话,那么assignoperator=有什么区别呢?如果它不复制,那么它是释放内存还是我的责任?

谢谢。

最佳答案

Does s.assign allocate a new buffer and copy the string into it or it assumes ownership of the pointer;

STL 字符串方法assign 会将字符数组复制到字符串中。如果字符串中已经分配的缓冲区不足,它将在内部重新分配内存。 STL 字符串将拥有原始数组的所有权。

If it copies, then what is the difference between assign and operator=?

两者的行为方式应该相同,但是 STL 的 assign 方法有许多重载,可以让您更好地控制发生的事情。看看this page了解更多信息。

更新:MSDN has a number of examples各种 assign 重载。

If it doesn't copy, then does it free the memory or it is my responsibility?

不,指向字符数组的原始指针仍然是你的责任。

关于c++ - std::string::assign 是否占用字符串的 "ownership"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3228906/

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