How to remove char * in C ++?

In my application, I create a char* as follows:

 class sample { public: char *thread; }; sample::sample() { thread = new char[10]; } sample::~sample() { delete []thread; } 

Am I doing the code correctly?

+4
source share
4 answers

List of marked items:

1) You need to allocate space for n characters, where n is the number of characters in the string, plus room for the final zero byte.

2) Then you changed the stream to point to another line. Therefore, you must use the delete[] function for the variable to be created using new[] .

But why are you fooling new and delete for character data? Why not just use std::string instead of the "C" functions? It's amazing why 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() . Even better, do not use char* and use std::string for string data.

+13
source

If you have [] after new , you need [] after delete . Your code looks correct.

+14
source

This is "correct" *, but it is very wrong.

You cannot use new[] , but use std::vector<char> or std::string instead. Even if you haven’t done this, you must follow the rule of three options , or your class does not work.

* Assuming you mean new char[10] . In addition, delete[] thread is more orthodox.

+2
source

Although this has nothing to do with memory management, there is one more thing to keep in mind. If you intend to define sample::sample and sample::~sample , you must first declare them, so your class definition should look something like this:

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

As @GMan said, you really shouldn't do this at all ...

+1
source

Source: https://habr.com/ru/post/1345809/


All Articles