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

Man*_*san 2 c++ string pointers char

我执行了下面的代码,它完美地运行.因为它是指针,我只想确定.虽然我确信将字符串赋值给字符串会产生副本,即使我删除了char*,字符串var也会保留该值.

    #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";
    }
Run Code Online (Sandbox Code Playgroud)

我只是在公司项目中更改了一些代码,而char*在C++中的函数之间传递.char*指针已复制到字符串,但char*在函数末尾被删除.我找不到任何具体原因.所以我只是删除char*,只要它被复制到一个字符串中.这会有什么问题......?

PS:我已经在Codereview中提出了这个问题,但我建议将其移至SO.所以我已将其标记为关闭并在此处发布问题.

Ton*_*ion 9

不,因为std::string复制了您的内容char*,所以当您不再需要它时,您可以自由删除它.


jua*_*nza 5

没有问题,只要newChar指向以null结尾的字符串,并且本身不为null.

std::string具有允许从一个隐式构造的构造函数const char*.它创建了由输入表示的字符串的副本,const char *因此它在假设char*空终止字符串的情况下工作,因为没有其他方法可以知道要复制到字符串自己的数据存储中的字符数.此外,NULL标准实际上不允许指针.