C ++:char指针指向std :: string转换是否复制内容? [英] C++ : Does char pointer to std::string conversion copy the content?

查看:134
本文介绍了C ++:char指针指向std :: string转换是否复制内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用构造函数将 char * 转换为 std :: string 时:

  char * ps =Hello; 
std :: string str(ps);

我知道std容器在被要求存储时往往会复制值。
是复制整个字符串还是仅指针?
如果后来我做 str =Bye会把ps改成指向Bye吗?

c>对象将分配内部缓冲区并将复制 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆