Hi!
I'm a little confused about deleting a variable in this case:
file String.hpp ...
file String.cpp ...Code:... class String { public: String(const char *text); ~String(); ... private: void setString(const char *text); void freeMem(void *mem); char *text; };
Testing the String classCode:# include ".\String.hpp" ... String::String() { text = new char('\0'); } String::~String() { freeMem(text); } void String::freeMem(void *mem) { delete mem; mem = NULL; } void String::setString(const char *text) { // delete previously allocated memory freeMem(text); // allocate a new memory int len = (int)strlen(text); this->text = new char[len + 1]; strncpy(this->text, text, len + 1); } ...
file main.cpp ...
Otherwise, is this design good?Code:# include ".\String.hpp" int main() { char *myText = new char[21]; strncpy(myText, "hello world!", 21); String s = myText; delete myText; // IS THIS CORRECT? myText = NULL; // if not, than where should I clear the memory? cout << s; return 0; }



LinkBack URL
About LinkBacks



CornedBee