Deleting char* after assigning it to a string variable(将 char* 分配给字符串变量后删除)
问题描述
我已经执行了下面的代码,它运行良好.由于它是关于指针的,我只是想确定一下.虽然我确信将 char* 分配给 string 会产生副本,即使我删除 char*,string var 也会保留该值.
I have executed the below code and it works perfectly. Since it is about pointers, I just want to be sure. Though I'm sure that assigning char* to string makes a copy and even if I delete char*, string var is gonna keep the value.
#include <stdio.h>
#include <string.h>
#include <string>
#include <iostream>
int main()
{
std::string testStr = "whats up ...";
int strlen = testStr.length();
char* newCharP = new char[strlen+1];
memset(newCharP,' ',strlen+1);
memcpy(newCharP,testStr.c_str(),strlen);
std::cout << " :11111111 : " << newCharP << "
";
std::string newStr = newCharP ;
std::cout << " 2222222 : " << newStr << "
";
delete[] newCharP;
newCharP = NULL;
std::cout << " 3333333 : " << newStr << "
";
}
我只是在我的公司项目中更改了一些代码,并且 char* 在 C++ 中的函数之间传递.char* 指针已复制到字符串,但 char* 在函数末尾被删除.我找不到任何具体的原因.所以我只是删除 char*,只要它被复制到一个字符串中.这会有什么问题吗...?
I'm just changing some code in my company project and char* are passed between functions in C++. The char* pointer has been copied to the string, but the char* is deleted in the end of the function. I couldn't find any specific reason for this. So I'm just deleting the char*, as soon as it is copied into a string. Would this make any problem ...?
P.S:我已经在 Codereview 中问过这个问题,但我得到了将其移至 SO 的建议.所以我已将其标记为关闭并在此处发布问题.
P.S : I have already asked this question in Codereview , but I got suggestion to move it to SO. So i have flagged it for close there and posting the question here.
推荐答案
没有问题,只要newChar
指向一个以null结尾的字符串,并且本身不为null.
There is no problem, as long as newChar
points to a null-terminated string, and is not null itself.
std::string
具有允许从 const char*
进行隐式构造的构造函数.它复制由输入 const char *
表示的字符串,因此它在假设 char*
是空终止字符串的情况下工作,因为没有其他知道将多少个字符复制到字符串自己的数据存储中的方法.此外,标准实际上不允许使用 NULL
指针.
std::string
has constructor that allows an implicit construction from a const char*
. It makes a copy of the character string represented by the input const char *
so it works under the assumption that the char*
is a null terminated string, since there is no other way to know how many characters to copy into the string's own data storage. Furthermore, a NULL
pointer is actually disallowed by the standard.
这篇关于将 char* 分配给字符串变量后删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 char* 分配给字符串变量后删除
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01