I have an older C program where I built a structure for a linked list
and I'm trying to make it C++, including using C++ constructs. I have
some questions on how strings work. Currently, the structure contains
char arrays but I'd rather they be strings, but I'm not clear on the details.
For example, when I want to copy an existing node to a new list
node, with char arrays (slist is the source list node), I (abbreviated):
tlist = new struct ENTRY; // Create a new instance of the list structure
tlist->title = new char[strlen(slist->title) + 1]; // Allocate memory
for the destination title string
if ( tlist->title == (char *)NULL ) // the allocation failed
cerr << "Failed to allocate new list data (" <<
(strlen(slist->title) + 1 ) << " bytes) for the title" << endl ;
else
strcpy(tlist->title, slist->title); // The allocation succeeded,
copy the source string to the destination string
------------------
Since I strcpy() the text to the new char array, the data is safe
if/when I delete [] the slist (source) entry.
With strings, I could set the title with either
tlist->title = slist->title;
OR
tlist->title.assign(slist->title);
I'm guessing the difference is similar to:
tlist->title = slist->title; // copy the ADDRESS of the source title
to the dest title; If the source title is delete[] ed, the
destination title is invalidated
If I assign() the title, I'm guessing it is similar to strcpy()ing
from the source to destination, and the source is still valid even if
I delete the source structure, slist.
So, I am assuming tlist->title.assign(slist->title); is the proper
way to "copy" the title string.
Can someone please confirm or deny and clarify my assumptions?
Also, to clear a string, I can use either:
string str;
str = "";
OR
str.clear();
I have read somewhere that clear() does not actually empty the
string, but my testing shows that it does. That is
str.clear();
if (str.empty())
cout << "The string is empty" << endl;
else
cout << "The string is not empty" << endl;
shows that the string is, in fact, empty.