将 char* 分配给字符串变量后删除

2022-01-12 00:00:00 string pointers char c++

我已经执行了下面的代码,它运行良好.由于它是关于指针的,我只是想确定一下.虽然我确信将 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.

相关文章