I'm building a String class, and I was wondering if in the constructor and the copy constructor I should copy the characters or just point to the same memory address as the passed char* / the char* of the copied String object ? This is what I wrote so far :
String::String(const char* pch) { str = const_cast<char*>(pch); length = getLen(); } String::String(const String& that) { length = that.length; str = new char[length]; for (unsigned int i = 0; i < length; i++) { str[i] = that.str[i]; } } In the constructor I'm just pointing to the same address as the const char*, should I leave it as that or copy each character into a new allocated memory block ? If I were to change the string I would allocated a new memory block anyway so the char* being const isn't much of a big deal (I think). In the copy constructor I copied each character to a new allocated memory space but I'm not sure it's necessary because if I would change the string later a new memory block will be allocated for the object that is changing leaving the other object with the same pointer untouched. Wanted to hear you opinions. "str" is of type char*.
std::string? (2) Always copy; string should be a "value" class. (3) You have no idea who owns the pointer that is passed in, nor when the string it points to could be deallocated. It is unsafe to retain a copy of the pointer!new char[](x)(and don't forget todelete []it accordingly of course). You can't mix that with simple pointer assignments as done in your other constructor.