How to delete char * in c++?
In my application, I create a char*
like this:
class sample
{
public:
char *thread;
};
sa开发者_运维百科mple::sample()
{
thread = new char[10];
}
sample::~sample()
{
delete []thread;
}
Am I doing the right thing in the code?
If you have []
after your new
, you need []
after your delete
. Your code looks correct.
List of points to be noted:
1) You need to allocate room for n characters, where n is the number of characters in the string, plus the room for the trailing null byte.
2) You then changed the thread to point to a different string. So you have to use delete[]
function for the variable you are created using new[]
.
But why are you fooling around with new
and delete
for character data? Why not just use std::string
, instead of 'C' functions? It's amazing why so many don't do the easiest thing:
#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]);
}
No need for new[]
, delete[]
, strcpy()
, etc.
Use strlen()
. Better yet, don't use char*
and use std::string
for string data.
It's "right"*, but it's very wrong.
You should not use new[]
, but instead use std::vector<char>
or std::string
. Even if you weren't doing that, you need to respect the rule of three, or your class is broken.
*Assuming you meant new char[10]
. Also, more orthodox is delete[] thread
.
精彩评论