C ++:char指针指向std :: string转换是否复制内容? [英] C++ : Does char pointer to std::string conversion copy the content?
问题描述
使用构造函数将 char *
转换为 std :: string
时:
char * ps =Hello;
std :: string str(ps);
我知道std容器在被要求存储时往往会复制值。
是复制整个字符串还是仅指针?
如果后来我做 str =Bye
会把ps改成指向Bye吗?
ps指向的字符串
。对该字符串的更改不会反映到 ps
缓冲区,反之亦然。它被称为深复制。如果仅复制指针本身而不复制存储器内容,则将其称为浅拷贝。 要重申: std :: string
在此情况下执行深度复制。
When I convert a char*
to std::string
using the constructor:
char *ps = "Hello";
std::string str(ps);
I know that std containers tend to copy values when they are asked to store them.
Is the whole string copied or the pointer only?
if afterwards I do str = "Bye"
will that change ps to be pointing to "Bye"?
std::string
object will allocate internal buffer and will copy the string pointed to by ps
there. Changes to that string will not be reflected to the ps
buffer, and vice versa. It's called "deep copy". If only the pointer itself was copied and not the memory contents, it would be called "shallow copy".
To reiterate: std::string
performs deep copy in this case.
这篇关于C ++:char指针指向std :: string转换是否复制内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!