在将char *赋给字符串变量后删除它 [英] Deleting char* after assigning it to a string variable
问题描述
我执行了下面的代码,它的工作完美。因为它是关于指针,我只是想确定。虽然我确信将字符串赋值给字符串会产生一个副本,即使我删除了char *,字符串变量也会保留该值。
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,'\0',strlen+1);
memcpy(newCharP,testStr.c_str(),strlen);
std::cout << " :11111111 : " << newCharP << "\n";
std::string newStr = newCharP ;
std::cout << " 2222222 : " << newStr << "\n";
delete[] newCharP;
newCharP = NULL;
std::cout << " 3333333 : " << newStr << "\n";
}
我只是更改公司项目中的一些代码,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 *赋给字符串变量后删除它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!