如何将 char 数组放入 std::string
我分配一个 char 数组,然后需要将其作为字符串返回,但我不想复制该 char 数组,然后释放其内存。
char* value = new char[required];
f(name, required, value, NULL); // fill the array
strResult->assign(value, required);
delete [] value;
我不想像上面那样做。我需要将数组放在标准字符串容器中。我怎样才能做到这一点?
编辑1:
我知道我不应该,并且该字符串不是为此目的而设计的。 MB 有人知道另一个 char 数组的容器实现吗?我可以用它来做到这一点?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C++11 中,以下内容保证有效:
在 C++03 中,不能保证有效,但可以通过 Library Issue 530 大多数标准库实现已经实施多年,因此它可能是安全的,但最终取决于实现。
In C++11, the following is guaranteed to work:
In C++03 that's not guaranteed to work, but it is addressed by Library Issue 530 which most standard library implementations have had implemented for years, so it's probably safe, but ultimately is implementation-dependent.
不要将
value
传递到函数中,而是传入&s[0]
,其中s
是std::string< /code> 长度正确。
Instead of passing
value
into the function, pass in&s[0]
, wheres
is astd::string
of the right length.你不应该。
std::strings
的设计目的不是公开其内部数据以用作缓冲区。不保证字符串的缓冲区地址在外部函数执行期间不会更改,尤其是在函数本身分配或释放内存的情况下。
并且不能保证字符串的缓冲区是连续的。
例如,请参阅此处。
您帖子中的示例是更好的方法。
You shouldn't.
std::strings
were not designed to expose their internal data to be used as a buffer.It's not guaranteed that the string's buffer address won't change during execution of an external function, especially not if the function allocates or deallocates memory itself.
And it's not guaranteed that the string's buffer is contiguous.
See, for example, here.
The example in your post is the better way to do it.
您必须将其复制到字符串中。 AFAIK std::string 不允许您访问它的内部目录来执行任何类型的基于地址的直接分配。
You're gonna have to copy it to a string. AFAIK std::string does not let you access it's internals directory to do any sort of an address based direct assignment.