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

时间:2011-03-30 03:22:23

标签: c++

在我的应用程序中,我创建了一个char*,如下所示:

class sample
{
    public:
        char *thread;
};

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

sample::~sample()
{
    delete []thread;
}

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

4 个答案:

答案 0 :(得分:16)

如果[]之后new [],则delete之后需要{{1}}。您的代码看起来是正确的。

答案 1 :(得分: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]);
}

无需new[]delete[]strcpy()等。

使用strlen()。更好的是,不要使用char*并使用std::string来获取字符串数据。

答案 2 :(得分:2)

这是“正确”*,但这是非常错误的。

您不应使用new[],而应使用std::vector<char>std::string。即使您没有这样做,您也需要尊重rule of three,否则您的课程就会崩溃。

*假设你的意思是new char[10]。此外,更正统的是delete[] thread

答案 3 :(得分:1)

虽然它与内存管理无关,但还有另外一点需要牢记。如果您要定义sample::samplesample::~sample,首先必须声明它们,因此您的类定义应如下所示:

class sample
{
    public:
        char *thread;
        sample();
        ~sample();
};

正如@GMan所说,你真的不应该这样做......

相关问题