我对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
是否分配一个新缓冲区并将字符串复制到其中,或者它假定指针的所有权;即不分配新内存并直接使用我的地址。如果是复制的话,那么assign
和operator=
有什么区别呢?如果它不复制,那么它是释放内存还是我的责任?
谢谢。
最佳答案
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/