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

标签 c++ string

我对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/

相关文章:

c++ - 不同的传参,不同的输出

c++ - 在 C++ 代码中查找悬空的 else

java - 使用字符串拆分时是否可以包含某种 OR 逻辑?

Python/Pandas 将字段字符串解包为多个字段

string - 使用 JSF 转换器输出时将 null 或空字符串替换为指定值

c++ - 如何使用配置模式进行 find_package 搜索并在模块模式下进行回退?

C++:访问冲突

c++ - 使用 vector 对象与创建自己的对象相比的优势

python - python 字符串连接问题

c# - 无需进行无数操作即可格式化字符串