0

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*.

9
  • 1
    (1) Why not use 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! Commented Sep 26, 2014 at 15:31
  • @cdhowie homework this is why :) and thanks didn't thought of the case that the memory will be deallocated. Commented Sep 26, 2014 at 15:39
  • @cdhowie forgot to ask, in the constructo the paramater is passed is const char*, if I were to create const char* I wouldn't be able to deallocate it because it's not being created with memory allocation functions so it won't be deallocated no ? so is it ok to leave it as is (talking about the constructor) Commented Sep 26, 2014 at 15:42
  • @Tugal.44 This won't work. You'll always need to allocate your internal buffer with new char[](x) (and don't forget to delete [] it accordingly of course). You can't mix that with simple pointer assignments as done in your other constructor. Commented Sep 26, 2014 at 15:44
  • 1
    You don't know the origin of the pointer, what if you store the address of a stack object that gets destroyed and later you try to read it? Commented Sep 26, 2014 at 15:50

1 Answer 1

1

Since you don't have control over the lifetime of the string whose pointer is passed to the constructor, it's unsafe to rely on it. Make a copy of the string.

Also since you don't know if the passed pointer was const or not, casting away constness as you do can lead to undefined behavior.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.