如何在c ++中删除char*?

kar*_*hik 7 c++

在我的应用程序中,我创建了char*这样的:

class sample
{
    public:
        char *thread;
};

sample::sample()
{
    thread = new char[10];
}

sample::~sample()
{
    delete []thread;
}
Run Code Online (Sandbox Code Playgroud)

我在代码中做了正确的事吗?

Fre*_*son 17

如果你有[]你的new,你需要[]在你的delete.您的代码看起来正确.


kar*_*hik 13

需要注意的要点清单:

1)您需要为n个字符分配空间,其中n是字符串中的字符数,以及尾随空字节的空间.

2)然后,您将线程更改为指向其他字符串.因此,您必须使用delete[]函数来创建使用的变量new[].

但是你为什么要newdelete角色数据一起玩呢?为什么不使用std::string,而不是'C'功能?令人惊讶的是,为什么这么多人不做最简单的事情:

#include <cstdio>
#include <string>

int countWords(const char *p);

int main(int argc, char *argv[])
{
    std::string pString = "The Quick Brown Fox!";

    int numWords1 = countWords(pString.c_str());
    printf("\n\n%d words are in the string %s", numWords1, pString.c_str());

    int numWords2 = countWords(argv[1]);
    printf("\n%d words are in the string %s", numWords2, argv[1]);
}
Run Code Online (Sandbox Code Playgroud)

无需new[],delete[],strcpy()等.

使用strlen().更好的是,不要使用char*和使用std::string字符串数据.

  • 不要将`strlen()`与`std :: string`一起使用.使用`.size()`成员函数 - 即使字符串嵌入了空字符,这也能正常工作.作为额外的奖励,它是O(1)! (5认同)